Fork me on GitHub

Minimum Window Substring

Description

https://leetcode.com/problems/minimum-window-substring/description/

Solution

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
82
83
84
85
86
87
88
89
90
91
92
class Solution:
def Valid(self, dic):
for item in dic.values():
if item > 0:
return False

return True



def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""

counter_t = {}
for ch in t:
if not counter_t.get(ch):
counter_t[ch] = 1
else:
counter_t[ch] += 1
counter_s = {}
for index in range(len(s)):
if not counter_s.get(s[index]):
counter_s[s[index]] = [[index], 0]
else:
counter_s[s[index]][0].append(index)

start = 0
while start < len(s):
if counter_t.get(s[start]) is None:
start += 1
continue
if counter_t.get(s[start]) >= 0:
break
counter_t[s[start]] -= 1
start += 1
print(counter_t)


end = start
while end < len(s):
if counter_t.get(s[end]) is not None:
counter_t[ s[end] ] -= 1

if not self.Valid(counter_t):
end += 1
else:
break

if not self.Valid(counter_t):
return ""
minum_start = start
minum_end = end
minum = end - start

while start <= end:
while start <= end:
if counter_t.get(s[start]) is None:
start += 1
continue

if counter_t.get(s[start]) >= 0:
break

counter_t[ s[start] ] += 1
start += 1
if end - start < minum:
minum_start = start
minum_end = end
minum = end - start
print(start, end, counter_t)

result_list = counter_s.get(s[start])
next_end = None
for index in range(result_list[1], len(result_list[0])):
if result_list[0][index] > end:
next_end = result_list[0][index]
result_list[1] = index + 1
break

if next_end is None:
break

for index in range(end + 1, next_end + 1):
if counter_t.get(s[index]) is not None:
counter_t[s[index]] -= 1
end = next_end

return s[minum_start: minum_end + 1]