You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
30 lines
706 B
30 lines
706 B
2 years ago
|
package class34;
|
||
|
|
||
|
public class Problem_0340_LongestSubstringWithAtMostKDistinctCharacters {
|
||
|
|
||
|
public static int lengthOfLongestSubstringKDistinct(String s, int k) {
|
||
|
if (s == null || s.length() == 0 || k < 1) {
|
||
|
return 0;
|
||
|
}
|
||
|
char[] str = s.toCharArray();
|
||
|
int N = str.length;
|
||
|
int[] count = new int[256];
|
||
|
int diff = 0;
|
||
|
int R = 0;
|
||
|
int ans = 0;
|
||
|
for (int i = 0; i < N; i++) {
|
||
|
// R 窗口的右边界
|
||
|
while (R < N && (diff < k || (diff == k && count[str[R]] > 0))) {
|
||
|
diff += count[str[R]] == 0 ? 1 : 0;
|
||
|
count[str[R++]]++;
|
||
|
}
|
||
|
// R 来到违规的第一个位置
|
||
|
ans = Math.max(ans, R - i);
|
||
|
diff -= count[str[i]] == 1 ? 1 : 0;
|
||
|
count[str[i]]--;
|
||
|
}
|
||
|
return ans;
|
||
|
}
|
||
|
|
||
|
}
|