非常好的two pointers的题; 下面是模版写法 (i作为右指针, left左)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
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() > k) {
char leftChar = s.charAt(left);
map.put(leftChar, map.get(leftChar) - 1);
if (map.get(leftChar) == 0) map.remove(leftChar);
left++;
}

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

return res;
}
}