YunheWang0813
3/14/2020 - 6:57 PM

0159. Longest Substring with At Most Two Distinct Characters

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        unordered_map<char, int> mp;
        int idx = 0, res = 0;
        for (int i = 0; i < s.size(); i++) {
            mp[s[i]]++;
            while (mp.size() > 2) {
                if (--mp[s[idx]] == 0) mp.erase(s[idx]);
                idx++;
            }
            res = max(res, i - idx + 1);
        }
        return res;
    }
};
// 二刷
// 自己做,bug free
class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        unordered_map<char, int> mp;
        int start = 0, last = 0, res = 0;
        while (start < s.size()) {
            mp[s[start]]++;
            while (mp.size() > 2) {
                if (--mp[s[last]] == 0) {
                    mp.erase(s[last]);
                }
                last++;
            }
            res = max(res, start - last + 1);
            start++;
        }
        return res;
    }
};