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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值