LeetCode 340. Longest Substring with At Most K Distinct Characters 双指针

本文深入探讨了寻找字符串中长度最长且包含最多k个不同字符的子串算法。通过实例解析,如输入s=ecebak=2,输出为3,解释了算法的实现细节与过程。同时,分享了作者在实现过程中的bug及解决方案,为读者提供了宝贵的编程经验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string, find the length of the longest substring T that contains at most k distinct characters.

Example 1:

Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.

Example 2:

Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.

-------------------------------------

没想明白自己为啥没有一次AC

class Solution:
    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
        if (k == 0):
            return 0
        l = len(s)
        x,y,curk,res = 0,0,0,0
        dic = {}
        for y in range(l):
            if (s[y] in dic):
                dic[s[y]] += 1
            else:
                curk += 1
                dic[s[y]] = 1
                while (curk > k):
                    dic[s[x]] -= 1
                    if (dic[s[x]] == 0):
                        curk -= 1
                        dic.pop(s[x]) #bug1: miss this line
                    x += 1
            res = max(res,y-x+1)
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值