Given a string, find the length of the longest substring T that contains at most 2 distinct characters.

For example, Given s = “eceba”,

T is "ece" which its length is 3.

Solution

public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        int count[] = new int[130];
        int left = 0, right = 0, maxLen = 0, cnt = 0;
        while(right < s.length()) {
            if(count[s.charAt(right++)]++ == 0) cnt++;
            while(cnt > 2) if(--count[s.charAt(left++)] == 0) cnt--;
            maxLen = Integer.max(maxLen, right - left);
        }
        return maxLen;
    }
}

results matching ""

    No results matching ""