Simple cpp solution similar to min window substring ; extensible


  • 0
    G
    public:
        int lengthOfLongestSubstringTwoDistinct(string s) {
            
            if(s.length() < 2)
                return s.length();
                
            vector<int> hasFound(256,0);
            int count = 0, idx = 0, maxLen = 0;
            
            for(int i = 0 ; i < s.length() ; i++){
                
                if(!hasFound[s[i]])
                    count++;
                    
                hasFound[s[i]]++;
                
                if(count <= 2){
                    //cout<<i<<" "<<idx<<endl;
                    maxLen = max(i-idx+1,maxLen);
                }
                
                if(count > 2){
                    while(--hasFound[s[idx]] != 0){
                        idx++;
                    }
                    idx++;
                    count--;
                }
            }
            return maxLen;
        }
    };
    

Log in to reply
 

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