Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 30fa1c3

Browse files
committed
feat: sliding window for 76 min window
1 parent 27171d9 commit 30fa1c3

File tree

3 files changed

+104
-0
lines changed

3 files changed

+104
-0
lines changed

‎src/76_minWindow/algo.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package algo
2+
3+
import "fmt"
4+
5+
func minWindow(s string, t string) string {
6+
if len(s) < len(t) {
7+
return ""
8+
}
9+
10+
need := map[byte]int{}
11+
for i := 0; i < len(t); i++ {
12+
need[t[i]] = need[t[i]] + 1
13+
}
14+
i := 0
15+
j := 0
16+
matchCount := 0
17+
result := ""
18+
for j < len(s) {
19+
// for match the condition
20+
for j < len(s) {
21+
c := s[j]
22+
if num, ok := count[c]; ok {
23+
if num == 0 {
24+
matchCount++
25+
}
26+
count[c] = num + 1
27+
}
28+
if matchCount != len(t) {
29+
j++
30+
} else {
31+
break
32+
}
33+
}
34+
if matchCount != len(t) {
35+
fmt.Println(i, j, matchCount, count)
36+
break
37+
}
38+
left:
39+
for i < len(s) {
40+
result = getMinSubstring(result, s, i, j+1)
41+
c := s[i]
42+
i++
43+
if num, ok := count[c]; ok {
44+
count[c] = num - 1
45+
if num == 1 {
46+
matchCount--
47+
break left
48+
}
49+
}
50+
}
51+
j++
52+
}
53+
return result
54+
}
55+
56+
func getMinSubstring(result, newString string, startIdx, endIdx int) string {
57+
if len(newString) < endIdx {
58+
endIdx = len(newString)
59+
}
60+
newString = newString[startIdx:endIdx]
61+
62+
if result != "" {
63+
if len(result) < len(newString) {
64+
return result
65+
} else {
66+
return newString
67+
}
68+
}
69+
return newString
70+
}

‎src/76_minWindow/algo_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package algo
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func TestMinWindow1(t *testing.T) {
9+
actual := minWindow("ADOBECODEBANC", "ABC")
10+
fmt.Println("actual: ", actual)
11+
}
12+
13+
// ADOBEC, 0,5
14+
// DOBEC, 1, 5
15+
// DOBECODEBA, 1,10, [1, 2, 1]
16+
// ODEBA,
17+
18+
func TestMinWindow2(t *testing.T) {
19+
actual := minWindow("a", "a")
20+
fmt.Println("actual: ", actual)
21+
}
22+
23+
func TestMinWindow3(t *testing.T) {
24+
actual := minWindow("a", "aa")
25+
fmt.Println("actual: ", actual)
26+
}
27+
28+
func TestMinWindow4(t *testing.T) {
29+
actual := minWindow("aa", "aa")
30+
fmt.Println("actual: ", actual)
31+
}

‎src/76_minWindow/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module algo
2+
3+
go 1.18

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /