-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubWithKUNiq.java
More file actions
30 lines (27 loc) · 866 Bytes
/
Copy pathLongestSubWithKUNiq.java
File metadata and controls
30 lines (27 loc) · 866 Bytes
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
import java.util.HashMap;
public class LongestSubWithKUNiq {
public int longestKSubstr(String s, int k) {
int i = 0, j = 0;
int ans = -1;
HashMap<Character, Integer> map = new HashMap<>();
while (j < s.length()) {
char ch = s.charAt(j);
map.put(ch, map.getOrDefault(ch, 0) + 1);
if (map.size() < k) {
j++;
} else {
if (map.size() == k) {
ans = Math.max(ans, j - i + 1);
} else {
map.put(s.charAt(i), map.get(s.charAt(i)) - 1);
if (map.get(s.charAt(i)) == 0) {
map.remove(s.charAt(i));
}
i++;
}
j++;
}
}
return ans;
}
}