comments | difficulty | edit_url | tags | |||
---|---|---|---|---|---|---|
true |
Medium |
|
Given a string s
, return the length of the longest substring that contains at most two distinct characters.
Example 1:
Input: s = "eceba" Output: 3 Explanation: The substring is "ece" which its length is 3.
Example 2:
Input: s = "ccaabbb" Output: 5 Explanation: The substring is "aabbb" which its length is 5.
Constraints:
1 <= s.length <= 105
s
consists of English letters.
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
cnt = Counter()
ans = j = 0
for i, c in enumerate(s):
cnt[c] += 1
while len(cnt) > 2:
cnt[s[j]] -= 1
if cnt[s[j]] == 0:
cnt.pop(s[j])
j += 1
ans = max(ans, i - j + 1)
return ans
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
Map<Character, Integer> cnt = new HashMap<>();
int n = s.length();
int ans = 0;
for (int i = 0, j = 0; i < n; ++i) {
char c = s.charAt(i);
cnt.put(c, cnt.getOrDefault(c, 0) + 1);
while (cnt.size() > 2) {
char t = s.charAt(j++);
cnt.put(t, cnt.get(t) - 1);
if (cnt.get(t) == 0) {
cnt.remove(t);
}
}
ans = Math.max(ans, i - j + 1);
}
return ans;
}
}
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
unordered_map<char, int> cnt;
int n = s.size();
int ans = 0;
for (int i = 0, j = 0; i < n; ++i) {
cnt[s[i]]++;
while (cnt.size() > 2) {
cnt[s[j]]--;
if (cnt[s[j]] == 0) {
cnt.erase(s[j]);
}
++j;
}
ans = max(ans, i - j + 1);
}
return ans;
}
};
func lengthOfLongestSubstringTwoDistinct(s string) (ans int) {
cnt := map[byte]int{}
j := 0
for i := range s {
cnt[s[i]]++
for len(cnt) > 2 {
cnt[s[j]]--
if cnt[s[j]] == 0 {
delete(cnt, s[j])
}
j++
}
ans = max(ans, i-j+1)
}
return
}