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向右滑動(dòng)一格仆嗦,然后用hash記錄字符數(shù),如果當(dāng)前substring.size() <= 2則記錄先壕,否則beg向右滑動(dòng)一格瘩扼,更新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;
}
};