386. 最多有k个不同字符的最长子字符串
给定字符串
S
,找到最多有k个不同字符的最长子串
T
。
样例
样例 1:
输入: S = "eceba" 并且 k = 3
输出: 4
解释: T = "eceb"
样例 2:
输入: S = "WORLD" 并且 k = 4
输出: 4
解释: T = "WORL" 或 "ORLD"
挑战
O(n) 时间复杂度
public class Solution {
/**
* @param s: A string
* @param k: An integer
* @return: An integer
*/
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int[] map = new int[126];
int size = 0;
int max = 0;
int end = 0;
int start = 0;
int len = s.length();
while (end < len) {
int c = s.charAt(end);
if (map[c] == 0) {
size++;
map[c]++;
while (size > k) {
c = s.charAt(start);
map[c]--;
if (map[c] <= 0) {
size--;
}
start++;
}
} else {
map[c]++;
}
max = Math.max(max, end - start + 1);
end++;
}
return max;
}
}