题解 | #至多包含K种字符的子串#

至多包含K种字符的子串

http://www.nowcoder.com/practice/04c926ef687340c3842a72edb5c23ede

哈希, 记录当前字符,当字符数多于 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
        
全部评论
看不明白。。。555
点赞 回复 分享
发布于 2022-11-15 19:07 北京

相关推荐

在打卡的大老虎很想潜...:你在找实习,没啥实习经历,技术栈放前面,项目多就分两页写,太紧凑了,项目你最多写两个,讲清楚就行,项目背景。用到的技术栈、亮点、难点如何解决,人工智能进面太难了,需求少。你可以加最新大模型的东西
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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