159. Longest Substring with At Most Two Distinct Characters

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.

tag: two pointers

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if (s == null || s.length() == 0) return 0;
        int k = 2;

        int j = 0;
        Map<Character, Integer> hash = new HashMap<>();
        int ans = 0;
        for (int i = 0; i < s.length(); i++){
            while (j < s.length()){
                char charJ = s.charAt(j);
                if (hash.containsKey(charJ)){
                    hash.put(charJ, hash.get(charJ) + 1);
                }
                else{
                    if (hash.size() == k) break;
                    hash.put(charJ, 1);
                }
                j++;
            }

            //System.out.println("j: " + j + " i: " + i);
            ans = Math.max(ans, j - i);

            char charI = s.charAt(i);
            hash.put(charI, hash.get(charI) - 1);
            if (hash.get(charI) == 0){
                hash.remove(charI);
            }
        }

        return ans;
    }
}

results for ""

    No results matching ""