您的位置:首页 > 其它

【LeetCode】Minimum Window Substring

2017-02-04 15:22 423 查看

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

我写的冗长版

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

思路

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

collections模块

  看看人家代码多么优雅,collections模块中一些常见函数的用法参见Python标准库——collections模块的Counter类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode string