【LeetCode】Minimum Window Substring

Description

  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.

Code

  1. 我写的冗长版
class Solution(object):
    def minWindow(self, s, t):
        def update(left, right, minL, s):
            while s[left] not in t:
                left += 1
            tmpL = right - left + 1
            if tmpL < minL:
                minL = tmpL
                return (True, s[left:right + 1], left, right, minL)
            return (False, None, left, right, minL)

        rst = ''
        if len(s) < len(t) or len(t) == 0:
            return rst
        dict = {}
        for ch in t:
            if ch in dict:
                dict[ch] += 1
            else:
                dict[ch] = 1
        minL = 111111111111

        left = 0
        store = {}
        cnt = 0 # 窗口中已经涵盖的字母数目

        for right in range(len(s)):
            if s[right] in dict:
                if s[right] in store:
                    store[s[right]] += 1
                else:
                    store[s[right]] = 1

                if store[s[right]] <= dict[s[right]]:
                    cnt += 1 # 把当前的词涵盖进去。如果这个词出现的次数已经多于要求的次数了,那就不用cnt++了,但是也先把这个词留着

                if cnt == len(t): # 都找到了!
                    (isShorter, rtn, left, right, minL) = update(left, right, minL, s)
                    if isShorter:
                        rst = rtn

                    for i in range(left, right):
                        if s[i] in store:
                            store[s[i]] -= 1
                            left = i + 1
                            if store[s[i]] >= dict[s[i]]:
                                (isShorter, rtn,left, right, minL) = update(left, right, minL, s)
                                if isShorter:
                                    rst = rtn
                            else: # 经过left的往右移动,现在window里面没能包含所有要求的字母,需要开始移动右边界了
                                cnt -= 1
                                break

        return rst

2.大神写的优雅版12 lines Python
    怎么说,感觉人家写得才是python……我好像写了假代码……

Note

  1. 思路
      这道题采用的“窗口”思路非常经典!!类似思路的还有Substring with Concatenation of All Words

  2. collections模块
      看看人家代码多么优雅,collections模块中一些常见函数的用法参见Python标准库——collections模块的Counter类

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值