File tree Expand file tree Collapse file tree 1 file changed +38
-16
lines changed Expand file tree Collapse file tree 1 file changed +38
-16
lines changed Original file line number Diff line number Diff line change @@ -2,30 +2,52 @@ package strings
2
2
3
3
import "fmt"
4
4
5
- func kmp (haystack , needle string ) []int {
6
- subsPositions := []int {}
7
- patternTable := fillTable (needle )
8
- fmt .Println ("FillTable: " , patternTable )
9
- return subsPositions
5
+ func KMP (haystack string , needle string ) int {
6
+ Nstr , Npattern := len (haystack ), len (needle )
7
+ if Nstr == 0 && Npattern == 0 || Npattern == 0 {
8
+ return 0
9
+ }
10
+ table := fillTable (needle )
11
+ fmt .Println (table )
12
+ str , pattern := 0 , 0
13
+
14
+ for str < Nstr {
15
+ if haystack [str ] == needle [pattern ] {
16
+ str ++
17
+ pattern ++
18
+ }
19
+ if pattern == Npattern {
20
+ return str - pattern
21
+ } else if str < Nstr && haystack [str ] != needle [pattern ] {
22
+ if pattern != 0 {
23
+ pattern = table [pattern - 1 ]
24
+ } else {
25
+ str ++
26
+ }
27
+ }
28
+
29
+ }
30
+ return - 1
10
31
}
11
32
12
33
func fillTable (needle string ) []int {
13
- lenNeedle := len (needle )
14
- table := make ([]int , lenNeedle )
15
- i , j := 0 , 1
34
+ n := len (needle )
35
+ table := make ([]int , n )
36
+ i := 0
37
+ j := 1
16
38
17
- for j < lenNeedle {
39
+ for j < n {
18
40
if needle [i ] == needle [j ] {
19
- table [j ] = table [ j - 1 ] + 1
41
+ table [j ] = i + 1
20
42
i ++
21
43
j ++
22
- continue
23
- }
24
- if i == 0 {
25
- table [j ] = i
26
- j ++
27
44
} else {
28
- i = table [i - 1 ]
45
+ if i != 0 {
46
+ i = table [i - 1 ]
47
+ } else {
48
+ table [j ] = 0
49
+ j ++
50
+ }
29
51
}
30
52
}
31
53
return table
You can’t perform that action at this time.
0 commit comments