C++ 3ms 6 lines simple solution using a sliding window


  • 0
    int lengthOfLongestSubstringTwoDistinct(string s) {
            int l = 0, r = 0, freqs[256]{}; 
            
            for (int num = 0; r < s.length(); r++) {                // maintaining a sliding window: [l, r]
                if (freqs[s[r]]++ == 0) { num++; }                  // num is the number of distinct chars          
                if (num > 2 && --freqs[s[l++]] == 0) { num--; }     // window size only increases if containing no more than 2 chars
            }
            
            return r - l;
    }
    

Log in to reply
 

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