159. 至多包含两个不同字符的最长子串 - 力扣(LeetCode)
典型的滑动窗口题型,使用哈希表:
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
unordered_map<char, int> map;
int len = 0;
int left = 0, right = 0;
while (right < s.size()){
auto c = s[right];
++right;
++map[c];
while (map.size() > 2){
auto d = s[left];
++left;
if (map[d] > 1) --map[d];
else if (map[d] == 1) map.erase(d);
}
len = max(len, right-left);
}
return len;
}
};