159. Longest Substring with At Most Two Distinct Characters

Given a string s, return the length of the longest substring that contains at most two distinct characters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Example 1:

Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.

Example 2:

Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.

Constraints:

  • 1 <= s.length <= 104
  • s consists of English letters.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        int start = 0;
        int end = 0;
        int maxLen = 0;
        int uniq = 0;
        int[] map = new int[128];
        
        while (end < s.length()) {
            char c = s.charAt(end);
            map[c]++;
            if (map[c] == 1) uniq++;
            end++;
            while (uniq > 2) {
                char prev = s.charAt(start);
                map[prev]--;
                if (map[prev] == 0) uniq--;
                start++;
            }
            maxLen = Math.max(maxLen, end - start);
        }
        return maxLen;
    }
}