Minimum Window Substring

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.

这题比较有意思,但是也比较坑,主要在于题目并没有说清楚如果T包含重复字符时应该如何处理。实际按题目本身的要求,T中字符重复出现在S的window中也需要有同样的出现次数。不考虑顺序只考虑出现次数,则可以先用hashmap存储T中的元素,做一个词频统计处理。之后在S中暴力做法是枚举window起点和终点,之后判断是否满足条件。自然想起用two pointer优化这题。

class Solution:
    """
    @param source: A string
    @param target: A string
    @return: A string denote the minimum window
             Return "" if there is no such a string
    """
    def minWindow(self, source, target):
        if not source:
            return ""
        hash = {}
        for i in target:
            if i not in hash:
                hash[i] = 1
            else:
                hash[i] += 1
        min_len = sys.maxint
        l = 0
        start = -1
        count = 0
        for r in xrange(len(source)):
            if source[r] in hash:
                hash[source[r]] -= 1
                if hash[source[r]] >= 0:
                    count += 1
                while count == len(target):
                    length = r - l + 1
                    if length < min_len:
                        min_len = length
                        start = l
                    if source[l] in hash:
                        hash[source[l]] += 1
                    if source[l] in hash and hash[source[l]] > 0:
                        count -= 1
                    l += 1
        return source[start: start + min_len] if start > -1 else ""

具体的难点在于有重复字符时如何判断窗口内是否已累计到需要的量的字符数目。所以以上代码采用了count这个变量来统计是否达到长度。 但是需要注意的是,一个window里面有多于T中某个字符出现频次的字符,count数不需要增加。具体来说因为开始hashmap中频率的值大于0,所以频率值小于0时说明已经出现了足够多的字符。 所以如果这时候字符在hashmap中,也不应该增加。之后在删除l 指针指向的字符时,同样,如果字符删除后,hash表中频率大于0了,说明这个字符影响了统计,所以count要减1.

转载于:https://www.cnblogs.com/sherylwang/p/5677475.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值