题解 | 至多包含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

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务