340. Longest Substring with At Most K Distinct Characters
class Solution:
def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
if k == 0:
return 0
M = defaultdict(int)
ss = set()
res = 0
l = - 1
for i in range(len(s)):
M[s[i]] += 1
if M[s[i]] == 1:
ss.add(s[i])
while len(ss) > k:
l += 1
M[s[l]] -= 1
if M[s[l]] == 0:
ss.remove(s[l])
res = max(res, i - l)
return res