哈希, 记录当前字符,当字符数多于 k 时,从上一个字符移动并调整哈希表中的值,直至符合条件

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @param k int整型 
# @return int整型
#
from collections import defaultdict
class Solution:
    def longestSubstring(self , s: str, k: int) -> int:
        # write code here
        count = defaultdict(int)
        start = 0
        max_l = 0
        for i, c in enumerate(s):
            count[c] += 1
            if len(count) <= k:
                max_l = max(max_l, i - start + 1)
            else:
                j = start
                while j < i - k + 1 and len(count) > k:
                    count[s[j]] -= 1
                    if count[s[j]] == 0:
                        del count[s[j]]
                    j += 1
                start = j
        return max_l