longest substring with at most k distinct characters


Longest Substring with At Most K Distinct Characters
这道题有意思的地方在于,就算map中unique的字符不到k,也得比较长度,否则就少算了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public int (String s, int k) {

if (s == null || s.length() == 0)
return 0;
HashMap<Character, Integer> map = new HashMap<>();
int left = 0, max = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
while (map.size() > k) {
c = s.charAt(left++);
map.put(c, map.get(c) - 1);
if (map.get(c) == 0) {
map.remove(c);
}
}
}
max = Math.max(max, i - left + 1);
}
return max;
}

wrong answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public int (String s, int k) {

if (s == null || s.length() == 0)
return 0;
HashMap<Character, Integer> map = new HashMap<>();
int left = 0, count = 0, max = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
++count;
}
if (count == k) {
int len = i - left + 1;
max = Math.max(len, max);
// move left
while (map.containsKey(s.charAt(left)) && map.get(s.charAt(left)) > 0) {
map.put(s.charAt(left), map.get(s.charAt(left)) - 1);
}
map.remove(s.charAt(left));
++left;
--count;
}
}
return max;
}