题解 | 至多包含K种字符的子串
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param s string字符串 # @param k int整型 # @return int整型 # class Solution: def longestSubstring(self , s: str, k: int) -> int: # write code here #给定一个长度为n的字符串s,找出最多包含 k 种不同字符的最长连续子串的长度 n=len(s) left=0 res=0 dic={} for right,x in enumerate(s): if x not in dic: dic[x]=1 else: dic[x]+=1 while len(dic)>k: dic[s[left]]-=1 if dic[s[left]]==0: del dic[s[left]] left+=1 res=max(res,right-left+1) return res