Skip to content

Commit 58485eb

Browse files
committed
update leetcode 28, add kmp solution
1 parent 3f40d14 commit 58485eb

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

src/0028.Implement-strStr-/README.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,49 @@ func strStr(haystack string, needle string) int {
5757
return -1
5858
}
5959
```
60-
### 思路2
6160

61+
### 思路 2
62+
KMP 算法
63+
```go
64+
func strStr(haystack string, needle string) int {
65+
prefixTable := calcPrefixTable(needle)
66+
67+
i, j := 0, 0
68+
for i < len(haystack) && j < len(needle) {
69+
if -1 == j || haystack[i] == needle[j] {
70+
i++
71+
j++
72+
} else {
73+
if j == 0 {
74+
i++
75+
} else {
76+
j = prefixTable[j]
77+
}
78+
}
79+
}
80+
if j == len(needle) {
81+
return i - j
82+
}
83+
return -1
84+
}
85+
86+
func calcPrefixTable(str string) []int {
87+
next := make([]int, len(str)+1)
88+
length := 0
89+
90+
for i := 2; i <= len(str); i++ {
91+
for length > 0 && str[length] != str[i-1] {
92+
length = next[length]
93+
}
94+
if str[length] == str[i-1] {
95+
length++
96+
}
97+
next[i] = length;
98+
}
99+
100+
return next
101+
}
102+
```
62103

63104
## 结语
64105

0 commit comments

Comments
 (0)