[leetcode]76. 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中所有字母在字符串s中出现的最短长度

1.统计t中所有字母出现的次数

2.用两个指针i,j遍历s,用missing统计还没遍历到的需要的字母的个数,用need字典统计还没遍历到的每个字母的个数

3.当missing为0时,更新结果

4.当j遍历到重复的需要的字母且missing为0时候,i往前移动

 1 class Solution(object):
 2     def minWindow(self, s, t):
 3         need,missing = collections.Counter(t),len(t)
 4         i,I,J = 0,0,0
 5         for j,c in enumerate(s,1):
 6             missing -= need[c]>0
 7             need[c] -= 1
 8             if not missing:
 9                 while i<j and need[s[i]]<0:
10                     need[s[i]] += 1
11                     i += 1
12                 if not J or j-i < J-I:
13                     I,J=i,j
14         return s[I:J]
原文地址:https://www.cnblogs.com/fcyworld/p/6504618.html