*76. Minimum Window Substring [Hard] 滑动窗口

17368230-862a03fdd0ce210f.png
76. Minimum Window Substring

使用滑动窗口
  主要思路是通过两次遍历找到所有可能的窗口(即从S中从start到end包含一个T),通过以下步骤实现:
  为了减少时间复杂度,用mp记录T中所有字符出现的次数,使用cnt在S中寻找时计数,一旦找到一个T中的字符,cnt--,同时mp中当前字符的次数减1,当cnt等于0时,即找到了一个包含T的字符串,通过比较每个找到的字符串的长度,选择最短字符串。

class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        mp = [0 for i in range(128)]
        #计算t中每个元素出现的次数
        for i in range(len(t)):
            mp[ord(t[i])] += 1
        #start end分别记录窗口的起止位置,res窗口大小,cnt表示t中还未包含的个数
        start = end = head = 0
        res = 2**31 - 1
        cnt = len(t)
        while end < len(s):
            #mp[i]>0表示i在T中且滑动窗口未全部包含,更新cnt和map
            if mp[ord(s[end])] > 0:
                cnt -= 1
            mp[ord(s[end])] -= 1
            end += 1
            #当前窗口T中的字符全部包含
            while cnt == 0:
                if end - start < res:
                    res = end - start
                    head = start
                #如果mp[i]==0,start后移之后,就不全部包含了,应该更新cnt
                if mp[ord(s[start])] == 0:
                    cnt += 1
                mp[ord(s[start])] += 1
                start += 1
        return '' if res == 2**31-1 else s[head:head+res]

参考了牛客网上大佬们的答案

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值