forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmp.go
49 lines (44 loc) · 742 Bytes
/
kmp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package kmp
// Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.
func Kmp(word, text string, patternTable []int) []int {
if len(word) > len(text) {
return nil
}
var (
i, j int
matches []int
)
for i+j < len(text) {
if word[j] == text[i+j] {
j++
if j == len(word) {
matches = append(matches, i)
i = i + j
j = 0
}
} else {
i = i + j - patternTable[j]
if patternTable[j] > -1 {
j = patternTable[j]
} else {
j = 0
}
}
}
return matches
}
// table building for kmp algorithm.
func table(w string) []int {
var (
t []int = []int{-1}
k int
)
for j := 1; j < len(w); j++ {
k = j - 1
for w[0:k] != w[j-k:j] && k > 0 {
k--
}
t = append(t, k)
}
return t
}