-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathLongestKUniqueCharactersSubstring.java
47 lines (37 loc) · 1.21 KB
/
LongestKUniqueCharactersSubstring.java
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
38
39
40
41
42
43
44
45
46
47
class Solution {
public int longestkSubstr(String str, int k) {
int i = -1, j = -1, ans = -1;
HashMap<Character, Integer> map = new HashMap<>();
while(true) {
boolean f1 = false, f2 = false;
// Acquire
while(i < str.length()-1) {
f1 = true;
i++;
char ch = str.charAt(i);
map.put(ch, map.getOrDefault(ch, 0) + 1);
if(map.size() == k+1) {
break;
} else if(map.size() == k){
if(ans < i-j) ans = i-j ;
}
}
// Release
while(j < i) {
f2 = true;
j++;
char ch = str.charAt(j);
if(map.get(ch) == 1) {
map.remove(ch);
} else {
map.put(ch, map.get(ch)-1);
}
if(map.size() == k) {
break;
}
}
if(!f1 && !f2) break;
}
return ans;
}
}