Problem
More LeetCode Discussions
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.
Solution
采用双指针的思想,beg和end,每次end向右滑动一格,然后用hash记录字符数,如果当前substring.size() <= 2则记录,否则beg向右滑动一格,更新hash直到substring.size <= 2为止。
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
if (s.size() == 0) {
return 0;
}
int beg = 0;
int end = 0;
map<char, int> count;
int maxLen = INT_MIN;
for(int end = 0; end < s.size(); end++) {
count[s[end]]++;
while (count.size() > 2) {
if (count[s[beg]] == 1) {
count.erase(count.find(s[beg]));
} else {
count[s[beg]]--;
}
beg++;
}
maxLen = max(maxLen, end - beg + 1);
}
return maxLen;
}
};