-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path064. LongestSubstringWithKUniques.java
More file actions
37 lines (34 loc) · 1 KB
/
064. LongestSubstringWithKUniques.java
File metadata and controls
37 lines (34 loc) · 1 KB
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
29
30
31
32
33
34
35
36
37
class Solution {
public int longestKSubstr(String s, int k) {
Map<Character, Integer> map = new HashMap<>();
int i = 0, j = 0, res = -1, countK = 0;
int n = s.length();
while (j < n) {
char ch = s.charAt(j);
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
countK++;
map.put(ch, 1);
}
if (countK < k)
j++;
else if (countK == k) {
res = Math.max(res, j - i + 1);
j++;
} else {
while (countK > k) {
int count = map.get(s.charAt(i));
if (count == 1) {
countK--;
map.remove(s.charAt(i));
} else
map.put(s.charAt(i), count - 1);
i++;
}
j++;
}
}
return res;
}
}