Longest Substring with At Most Two(K) Distinct Characters
Input: "eceba"
Output: 3
Explanation: "ece"Input: "ccaabbb"
Output: 5
Explanation: "aabbb" public int lengthOfLongestSubstringTwoDistinct(String s) {
if (s == null || s.length() == 0) return 0;
int maxlen = 0, j = 0;
Map<Character, Integer> countMap = new HashMap<>();
// i是不断移动的右坐标,j是需要移动时才移动的左坐标
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
countMap.put(c, countMap.getOrDefault(c, 0) + 1);
while (countMap.size() > 2 && j <= i) {
char chj = s.charAt(j);
// 把在j指针位置的字母个数减1或者删去,移动j指针
if (countMap.get(chj) == 1) countMap.remove(chj);
else countMap.put(chj, countMap.get(chj) - 1);
j++;
}
// 更新最大值
maxlen = Math.max(maxlen, i - j + 1);
}
return maxlen;
}Last updated