[Leetcode]76. Minimum Window Substring @python

题目

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).

For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.

Note:
If there is no such window in S that covers all characters in T, return the empty string “”.

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

题目要求

给定字符串s和目标字符串t,要在s中找到一个最小的窗口,其中出现了所有t中的字符。

解题思路

解这道题需要注意,t中的字符可能为重复字符,所以需要用字典记录每个字符出现的次数。要判断窗口中是否出现了所有字符,首先需要左右指针表示窗口的位置,同时要有另外一个字典记录窗口中每个字符出现的次数。另外一个变量记录窗口中t内的字符出现的次数。

代码

class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        count = len(t)
        minileft = 0
        miniSize = len(s) + 1
        left = 0
        cmap1 = {}
        cmap2 = {}
        for c in t:
            if c not in cmap1:
                cmap1[c] = 1
                cmap2[c] = 1
            else:
                cmap1[c] += 1
                cmap2[c] += 1

        for right in range(len(s)):
            if s[right] in cmap1:
                cmap2[s[right]] -= 1
                if cmap2[s[right]] >= 0:
                    count -= 1
                if count == 0:
                        while True:
                            if s[left] in cmap2:
                                if cmap2[s[left]] < 0:
                                    cmap2[s[left]] += 1
                                else:
                                    break 
                            left += 1

                        if right - left + 1 < miniSize:
                            minileft = left
                            miniSize = right - minileft + 1

        if miniSize < len(s) + 1:
            return s[minileft:minileft + miniSize]
        else:
            return ''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值