Problem

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: t is "ece" which its length is 3.
Example 2:

Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.

Solution

class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if (s == null || s.length() == 0) return 0;
        Map<Character, Integer> map = new HashMap<>();
        int i = 0, j = 0, len = s.length(), max = 0;
        char[] str = s.toCharArray(); //char[] is much faster
        while (j < len) {
            map.put(str[j], j);
            j++;
            if (map.size() > 2) {
                int leftMost = len;
                for (int index: map.values()) leftMost = Math.min(leftMost, index);
                map.remove(str[leftMost]);
                i = leftMost+1;
            }
            max = Math.max(max, j-i);
        }
        return max;
    }
}

linspiration
161 声望53 粉丝