essentially the same as LC340. Longest Substring with at Most K Distinct Characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int res = 0, left = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);

while (map.size() > 2) {
char leftChar = s.charAt(left);
map.put(leftChar, map.get(leftChar) - 1);
if (map.get(leftChar) == 0) map.remove(leftChar);

left ++;
}
res = Math.max(res, i - left + 1);
}

return res;
}
}