题解 | #最小覆盖子串#

最小覆盖子串

https://www.nowcoder.com/practice/c466d480d20c4c7c9d322d12ca7955ac

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param S string字符串 
# @param T string字符串 
# @return string字符串
#
class Solution:

    def check(self,hash):  # 检查是否都出现过
        for i in hash:
            if hash[i] <= 0:
                return False
        return True

    def minWindow(self , S: str, T: str) -> str:
        hash = {}
        for char in T:
            if char in hash:
                hash[char] -= 1
            else:
                hash[char] = 0
        res_len = 999
        res = ''

        i = 0 #右
        j = 0 #左
        while i < len(S):
            while not self.check(hash): # 检查是否满足都出现过
                if S[i] in hash:
                    hash[S[i]] += 1
                i += 1
                if i == len(S) and not self.check(hash): # 到最后的还不满足,可以直接返回
                    return res
            while self.check(hash): # 移动左指针。如果不满足就停
                if S[j] in hash:
                    hash[S[j]] -= 1
                j += 1
            len_tmp = i-(j-1) # j要-1才满足
            if len_tmp < res_len:
                res_len = len_tmp
                res = S[j-1:i]
        return res

全部评论

相关推荐

04-11 23:51
门头沟学院 Java
坚定的芭乐反对画饼_许愿Offer版:人人都能过要面试干嘛,发个美团问卷填一下,明天来上班不就好了
点赞 评论 收藏
分享
大叔叔1:你把自己说的话打码,所以你想表达什么
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务