Leetcode 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.




    public int lengthOfLongestSubstringTwoDistinct(String s) {
        Map map = new HashMap<>();
        int start = 0, end = 0, maxLength = 0, cnt = 0;
        
        while (end < s.length()) {
            char c = s.charAt(end);
            map.put(c, map.getOrDefault(c, 0) + 1);
            if (map.get(c) == 1) cnt++;
            end++;
            while (cnt > 2) {
                char tmp = s.charAt(start);
                map.put(tmp, map.get(tmp) - 1);
                if (map.get(tmp) == 0) cnt--;
                start++;
            }
            maxLength = Math.max(maxLength, end - start);
        }
        return maxLength;
    }





你可能感兴趣的:(Leetcode)