-
Notifications
You must be signed in to change notification settings - Fork 0
/
0076_min_window_substr.py
61 lines (52 loc) · 1.38 KB
/
0076_min_window_substr.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
"""
neetcode - sliding window - 5
sol:
count chars in t
use two pointers for sliding window
expand right until window has all needed in ct
contract left until window doesn't, updating min
"""
from collections import defaultdict
class Solution:
def minWindow(self, s: str, t: str) -> str:
ct = defaultdict(int)
cc = defaultdict(int)
for char in t:
ct[char] += 1
cc[char] = 0
have = 0
need = len(ct)
i = 0
j = 0
ml = len(s)
ms = ""
while True:
# expand right until substring has at least all in ct
while have < need:
if j >= len(s):
return ms
if s[j] in ct:
cc[s[j]] += 1
if cc[s[j]] == ct[s[j]]:
have += 1
j += 1
# reduce left
while have >= need:
if j - i <= ml:
ml = j - i
ms = s[i:j]
if s[i] in ct:
if cc[s[i]] == ct[s[i]]:
have -= 1
cc[s[i]] -= 1
i += 1
s = Solution()
print(s.minWindow("ADOBECODEBANC", "ABC"))
print()
print(s.minWindow("a", "a"))
print()
print(s.minWindow("a", "aa"))
print()
print(s.minWindow("ab", "a"))
print()
print(s.minWindow("aa", "aa"))