C++_AC_map+two pointers


  • 0

    But is there any more efficient method? My AC time only beats less than 20% ppl.

    class Solution {
    public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        if(s.size() <= 2) return s.size();
        unordered_map<char,int> mp;
        int res = INT_MIN, i = 0, j = 0;
        while(j < s.size()){
            if(mp.find(s[j]) == mp.end()){
                while(mp.size() >= 2){
                    mp[s[i]]--;
                    if(mp[s[i]] == 0) mp.erase(s[i]);
                    i++;
                }
            }
            mp[s[j++]]++;
            res = max(res, j - i);
        }
        return res;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.