0
点赞
收藏
分享

微信扫一扫

【leetcode】 340 Longest Substring with At Most K Distinct Characters

_铁马冰河_ 2022-01-10 阅读 69

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
};
举报

相关推荐

0 条评论