C++ 3 ms AC with 2 pointer


  • 1
    F
    int lengthOfLongestSubstringTwoDistinct(string s) {
            if(s.empty())return 0;
            int mp[256]={0};
            int len = s.size();
            int cnt=0,ans=0;
            int i=-1;
            for(int j=0;j<len;j++){
                mp[ s[j] ]++;
                if(mp[ s[j] ]==1){
                    cnt++;
                }
                while(cnt>2){
                    mp[ s[++i] ] --;
                    if(mp[ s[i] ]==0)cnt--;
                }
                ans = max(ans , j-i);
            }
            return ans;
        }
    

Log in to reply
 

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