Longest Substring with At Most Two Distinct Characters

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

Example 1:
Input: "eceba"
Output: 3
Explanation: tis "ece" which its length is 3.
Example 2:
Input: "ccaabbb"
Output: 5
Explanation: tis "aabbb" which its length is 5.

  • Code
 public int lengthOfLongestSubstringTwoDistinct(String s) {
        int res = 0, left = 0;
        HashMap hash = new HashMap();
        for (int i = 0; i < s.length(); i++) {
            Character tmp = s.charAt(i);
            hash.put(tmp, hash.getOrDefault(tmp, 0) + 1);
            while (hash.size() > 2) {
                Character leftChar = s.charAt(left);
                int cnt = hash.get(leftChar) - 1;

                hash.put(leftChar, cnt);

                if (cnt == 0) {
                    hash.remove(leftChar);
                }
                left++;
            }
            res = Math.max(res, i - left + 1);
        }
        return res;
    }

你可能感兴趣的:(Longest Substring with At Most Two Distinct Characters)