#76 Minimum Window Substring——Top 100 Liked Questions

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:

  • If there is no such window in S that covers all characters in T, return the empty string "".
  • If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

"""

第一次:移动窗口法:设置left和right两个指针,当t的字符没有全都包含在窗口(left与right之间)中时,向右移动right, 当窗口中包含t时,此时向右移动left指针,每移动一次left,判断此时窗口是否还包含t,当包含时,left指针继续右移,否则记录此时left与right的位置,与保存窗口信息的res比较,更新最短窗口信息。主要思考:怎么验证窗口中否全都包含了t?采用字典,记录每个字母出现的次数,看t中字母出现的次数是否与窗口中的次数相同!
"""

from collections import Counter
class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        if not s or not t:
            return ""
        Ls = len(s)
        left, right = 0, 0
        res = float("inf"), left, right
        sWindowCount = {}
        tCount = Counter(t)        flag = 0
        while right < Ls:
            sWindowCount[s[right]] = sWindowCount.get(s[right], 0) + 1
            if s[right] in tCount and sWindowCount[s[right]] == tCount[s[right]]:
                flag += 1
            while flag == Ltc and left <= right:
                if right - left + 1 < res[0]:
                    res = right - left + 1, left, right
                sWindowCount[s[left]] -= 1
                if s[left] in tCount and sWindowCount[s[left]] < tCount[s[left]]:
                    flag -= 1
                left += 1
            right += 1
        return "" if res[0] == float("inf") else s[res[1]: res[2] + 1]

"""

Runtime: 116 ms, faster than 65.73% of Python online submissions forMinimum Window Substring.

Memory Usage: 12.4 MB, less than 93.71% of Python online submissions forMinimum Window Substring.

"""

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值