Longest Substring with At Most Two(K) Distinct Characters
LC. 159 & 340
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: "ece"
Example 2:
Input: "ccaabbb"
Output: 5
Explanation: "aabbb"
My Solutions:
无论是找最多2个字母还是k个字母,都是用hashmap记录每个字母出现的字数。如果hashmap的长度超过了2个(k个),需要删掉一个entry,并且移动左坐标。
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