-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 160.java
More file actions
35 lines (28 loc) · 850 Bytes
/
Day 160.java
File metadata and controls
35 lines (28 loc) · 850 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
31
32
33
34
35
class Solution {
public int longestKSubstr(String s, int k) {
int n = s.length();
int[] freq = new int[26];
int left = 0;
int distinct = 0;
int maxLen = -1;
for (int right = 0; right < n; right++) {
char c = s.charAt(right);
if (freq[c - 'a'] == 0) {
distinct++;
}
freq[c - 'a']++;
while (distinct > k) {
char leftChar = s.charAt(left);
freq[leftChar - 'a']--;
if (freq[leftChar - 'a'] == 0) {
distinct--;
}
left++;
}
if (distinct == k) {
maxLen = Math.max(maxLen, right - left + 1);
}
}
return maxLen;
}
}