Skip to content

Commit e4772e8

Browse files
committed
28. Implement strStr()
1 parent 44542c5 commit e4772e8

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

implement_strstr/main.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package leecode
2+
3+
const base = 16777619
4+
5+
func hash(s string) uint32 {
6+
var h uint32
7+
for i := 0; i < len(s); i++ {
8+
h = (h*base + uint32(s[i]))
9+
}
10+
return h
11+
}
12+
13+
func strStr(haystack string, needle string) int {
14+
n := len(haystack) // string len
15+
m := len(needle) // pattern len
16+
switch {
17+
case m == 0:
18+
return m
19+
case n == m:
20+
if haystack == needle {
21+
return 0
22+
}
23+
return -1
24+
case m > n:
25+
return -1
26+
}
27+
pattern := hash(needle)
28+
29+
for i := 0; i < (n-m)+1; i++ {
30+
substr := haystack[i : i+m]
31+
hs := hash(substr)
32+
if hs == pattern {
33+
return i
34+
}
35+
}
36+
return -1
37+
}

implement_strstr/main_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package leecode
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
var testCases = []struct {
9+
Haystack string
10+
Needle string
11+
Output int
12+
}{
13+
{
14+
Haystack: "hello",
15+
Needle: "ll",
16+
Output: 2,
17+
},
18+
}
19+
20+
func TestStrStr(t *testing.T) {
21+
for _, tc := range testCases {
22+
t.Run(fmt.Sprintf("%s %s %d", tc.Haystack, tc.Needle, tc.Output), func(t *testing.T) {
23+
actual := strStr(tc.Haystack, tc.Needle)
24+
if actual != tc.Output {
25+
t.Errorf("expects: %d gets: %d", tc.Output, actual)
26+
}
27+
})
28+
}
29+
}
30+
31+
func BenchmarkStrStr(b *testing.B) {
32+
for _, tc := range testCases {
33+
// run the Fib function b.N times
34+
b.Run(fmt.Sprintf("%s %s %d", tc.Haystack, tc.Needle, tc.Output), func(b *testing.B) {
35+
for n := 0; n < b.N; n++ {
36+
strStr(tc.Haystack, tc.Needle)
37+
}
38+
})
39+
}
40+
}

0 commit comments

Comments
 (0)