Skip to content

Commit 6a6e48e

Browse files
committed
76. minimum window substring
1 parent 62d084b commit 6a6e48e

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

76.minimum-window-substring.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package leetcode
2+
3+
/*
4+
* @lc app=leetcode id=76 lang=golang
5+
*
6+
* [76] Minimum Window Substring
7+
*/
8+
9+
// @lc code=start
10+
func minWindow(s string, t string) string {
11+
12+
// init
13+
// 1. init tMap
14+
tMap := make(map[byte]int)
15+
for i := 0; i < len(t); i++ {
16+
tMap[t[i]]++
17+
}
18+
// 2. init sMap
19+
sMap := make(map[byte]int)
20+
// 3. init left, right, minLen, minLeft
21+
left, right, minLen, minLeft := 0, 0, len(s)+1, 0
22+
// 4. init valid
23+
valid := 0
24+
25+
// loop
26+
for right < len(s) {
27+
// 1. add right
28+
c := s[right]
29+
right++
30+
// 2. update sMap
31+
if _, ok := tMap[c]; ok {
32+
sMap[c]++
33+
if sMap[c] == tMap[c] {
34+
valid++
35+
}
36+
}
37+
// 3. shrink left
38+
for valid == len(tMap) {
39+
// 3.1 update minLen, minLeft
40+
if right-left < minLen {
41+
minLen = right - left
42+
minLeft = left
43+
}
44+
// 3.2 remove left
45+
d := s[left]
46+
left++
47+
// 3.3 update sMap
48+
if _, ok := tMap[d]; ok {
49+
if sMap[d] == tMap[d] {
50+
valid--
51+
}
52+
sMap[d]--
53+
}
54+
}
55+
}
56+
57+
// return
58+
if minLen == len(s)+1 {
59+
return ""
60+
}
61+
return s[minLeft : minLeft+minLen]
62+
}
63+
64+
// @lc code=end

0 commit comments

Comments
 (0)