-
Notifications
You must be signed in to change notification settings - Fork 0
/
340
28 lines (28 loc) · 895 Bytes
/
340
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
//https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
if(s == null || k == 0) return 0;
int [] dict = new int[256];
int count = 0;
int ret = 0;
int last = 0;
for(int i = 0; i< s.length(); ++i) {
int index = (int)s.charAt(i);
if(dict[index] == 0) count++;
dict[index] ++;
if(count<=k) {
if(i - last + 1 > ret)
ret = i - last + 1;
} else {
while(count>k) {
int l = (int)s.charAt(last);
dict[l] --;
last ++;
if(dict[l] == 0)
count--;
}
}
}
return ret;
}
}