File tree Expand file tree Collapse file tree 1 file changed +42
-1
lines changed
src/0028.Implement-strStr- Expand file tree Collapse file tree 1 file changed +42
-1
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments