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