Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
Example 1:
Input: s = “eceba”, k = 2
Output: 3
Explanation: The substring is “ece” with length 3.
Example 2:
Input: s = “aa”, k = 1
Output: 2
Explanation: The substring is “aa” with length 2.
滑动窗口+map。 map中存每个字母出现的频率,可以用一个counter记录当前的子串中有几种字母,也可以删除map中频率为0的字母,这样map的length就是子串中字母种类。这里采用前者。
循环时右指针依次把字母存到map中,同时增加counter,如果增加后的counter大于k了,则不断移动左指针直到子串中不再包含某个字母,此时counter 等于 k。在整个过程中不断更新最大的子串长度。
var lengthOfLongestSubstringKDistinct = function(s, k) {
if(k === 0) {
return 0
}
//sliding window
let right = 0, left = 0;
let res = 0;
let counter = 0;
const map = {};
while(right < s.length) {
if(!map[s[right]]) {
map[s[right]] = 1;
counter++;
} else {
map[s[right]] ++;
}
while(counter > k) {
map[s[left]] --;
if(map[s[left]] === 0) {
counter--;
}
left++
}
res = Math.max(res, right - left + 1);
right++;
}
return res
};