Longest Substring with At Most Two Distinct Characters

Hard

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.

Related Problems

Longest Substring with At Most K Distinct Characters

Analysis

Same as Longest Substring with At Most K Distinct Characters, when k = 2.

Sliding window two pointer technique.

Solution

Sliding Window - Two Pointers (15 ms, faster than 22.97%)

class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] chs = s.toCharArray();
int n = s.length();

HashMap<Character, Integer> count = new HashMap<>();

int longest = 0;

int firstIdx = 0;

for (int i = 0; i < n; i++) {
count.put(chs[i], count.getOrDefault(chs[i], 0) + 1);
while (count.size() > 2) {
count.put(chs[firstIdx], count.get(chs[firstIdx]) - 1);
if (count.get(chs[firstIdx]) == 0) {
count.remove(chs[firstIdx]);
}
firstIdx++;
}
longest = Math.max(longest, i - firstIdx + 1);
}
return longest;
}
}