Skip to content

Commit 0ba0f5d

Browse files
Adding KMP Algo
1 parent d80e64e commit 0ba0f5d

File tree

1 file changed

+38
-16
lines changed

1 file changed

+38
-16
lines changed

Go/strings/kmp.go

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,52 @@ package strings
22

33
import "fmt"
44

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
1031
}
1132

1233
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
1638

17-
for j < lenNeedle {
39+
for j < n {
1840
if needle[i] == needle[j] {
19-
table[j] = table[j-1] + 1
41+
table[j] = i + 1
2042
i++
2143
j++
22-
continue
23-
}
24-
if i == 0 {
25-
table[j] = i
26-
j++
2744
} else {
28-
i = table[i-1]
45+
if i != 0 {
46+
i = table[i-1]
47+
} else {
48+
table[j] = 0
49+
j++
50+
}
2951
}
3052
}
3153
return table

0 commit comments

Comments
 (0)