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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import sys
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
m = collections.Counter(t)
start = 0
min_start = 0
end = 0
counter = len(t)
min_len = sys.maxsize
while end < len(s):
if m[s[end]] > 0:
counter -= 1
m[s[end]] -= 1
end += 1
while counter == 0:
if end - start < min_len:
min_len = end - start
min_start = start
m[s[start]] += 1
if m[s[start]] > 0:
counter += 1
start += 1
if min_len == sys.maxsize:return ''
return s[min_start:min_start+min_len]