-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path76_MinimumWindowSubstring.py
executable file
·72 lines (63 loc) · 2.16 KB
/
76_MinimumWindowSubstring.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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def minWindow(self, s, t):
s_size = len(s)
if not t or not s:
return ""
# Keep the present tims of all characters in T.
t_dict = {}
for char in t:
if char not in t_dict:
t_dict[char] = 1
else:
t_dict[char] += 1
count = 0
t_size = len(t)
start = end = 0
# min_window(start, end): the suitable window's left and right board
min_window = (0, s_size)
# Keep the present tims of the window's characters that appear in T.
win_dict = {}
while end < s_size:
cur_char = s[end]
if cur_char in t_dict:
if cur_char not in win_dict:
win_dict[cur_char] = 1
else:
win_dict[cur_char] += 1
if win_dict[cur_char] <= t_dict[cur_char]:
count += 1
if count == t_size:
# Move start toward to cut the window's size.
is_suitable_window = True
while start <= end and is_suitable_window:
start_char = s[start]
if start_char not in t_dict:
start += 1
else:
if win_dict[start_char] > t_dict[start_char]:
win_dict[start_char] -= 1
start += 1
else:
is_suitable_window = False
# Update the minimum window
window_size = end - start + 1
min_size = min_window[1] - min_window[0] + 1
if window_size < min_size:
min_window = (start, end)
# Move start toward to find another suitable window
win_dict[s[start]] -= 1
start += 1
count -= 1
end += 1
# No suitable window
if min_window[1] == s_size:
return ""
return s[min_window[0]: min_window[1] + 1]
"""
"a"
""
"ADOBECODEBANC"
"ABCC"
"""