-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimum_window_substring.py
82 lines (62 loc) · 1.37 KB
/
minimum_window_substring.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from collections import Counter
#
# https://leetcode.com/problems/minimum-window-substring
#
def minimum_window_substring(s, t):
ll = len(s)
lll = len(t)
if lll > ll:
return ""
counter = Counter(t)
cur_counter = Counter()
min_len = ll
l, r = 0, ll
seen = False
start = 0
for idx in xrange(ll):
if s[idx] not in counter:
continue
cur_counter[s[idx]] += 1
should_check = all(cur_counter.get(k, 0) >= counter.get(k)
for k in counter)
if not should_check:
continue
seen = True
while True:
if s[start] in cur_counter:
cur_counter[s[start]] -= 1
if 1 + cur_counter[s[start]] == counter.get(s[start]):
cur_counter[s[start]] += 1
break
start += 1
if start >= idx:
break
cur_len = idx + 1 - start
if 0 <= cur_len < min_len:
min_len = cur_len
l = start
r = idx + 1
if not seen:
return ""
else:
return s[l:r]
# S = "ADOBECODEBANC"
# T = "ABDC"
S = "BCDAAQA"
T = "AQA"
# #
# S = "BCDAAQA"
# T = "ADQ"
# #
S = "BB"
T = "BB"
# #
# S = "BBB"
# T = "BB"
# #
# S = "ABC"
# T = "BA"
# #
# S = "ABC"
# T = "BC"
print minimum_window_substring(S, T)