159. Longest Substring with At Most Two Distinct Characters
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s =“eceba”,
T is "ece" which its length is 3.
Thoughts
count: count # of distinct characters
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int left = 0, right = 0, count = 0, len = 0;
unordered_map <char, int> map;
while(right < s.length()){
// put, check new
if(++map[s[right]] == 1) count++;
right++;
// move left to reduce the window size if
// there are more than two distinct chars in the current window
while(count > 2){
if(--map[s[left]] == 0) count--;
left++;
}
len = max(len, right - left);
}
return len;
}
};template
Previous30. Substring with Concatenation of All WordsNext340. Longest Substring with At Most K Distinct Characters
Last updated
Was this helpful?