Longest Substring with At Most Two Distinct Characters
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example,
Given s = “eceba”,
T is "ece" which its length is 3.
Solution
public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) return 0;
int result = Integer.MIN_VALUE;
Map<Character, Integer> map = new HashMap<>();
int startIndex = 0;
int endIndex = 0;
while (endIndex < s.length()) {
Character currentChar = s.charAt(endIndex);
map.merge(currentChar, 1, (a, b) -> a + b);
if (map.size() <= 2) {
result = Math.max(result, endIndex - startIndex + 1);
} else {
// move startIndex
while (map.size() > 2) {
Character removeChar = s.charAt(startIndex);
map.merge(removeChar, 1, (a,b)->a-b);
if (map.get(removeChar) == 0) {
map.remove(removeChar);
}
startIndex ++;
}
}
endIndex ++;
}
return result;
}
}