159.Longest Substring with At Most Two Distinct Characters

1- Slide Widow

No.3, No.76

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        int[] map = new int[128];
        int cnt = 0;
        int begin = 0;
        int end = 0;
        int maxLength = 0;
        while(end < s.length()){
            map[s.charAt(end)]++;
            if(map[s.charAt(end)] == 1){
                cnt++;
                while(cnt > 2){
                    map[s.charAt(begin)]--;
                    if(map[s.charAt(begin)] == 0)
                        cnt--;
                    begin++;
                }
            }
            maxLength = Math.max(maxLength, end - begin + 1);
            end++;
        }
        return maxLength;
    }
}

results matching ""

    No results matching ""