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

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

被折叠的 条评论
为什么被折叠?



