-
Notifications
You must be signed in to change notification settings - Fork 0
/
kmp.go
65 lines (56 loc) · 865 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// Information about the algorithm is available on Wikipedia
//
// https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
//
package kmp
// Search for pattern in given input and returns slice of matche indicies
func Search(input string, pattern string) []int {
var (
M = len(pattern)
N = len(input)
)
if N == 0 || M == 0 {
return nil
}
var (
result = make([]int, 0)
l = 0
i = 1
j = 0
lps = make([]int, M)
)
for ; i < M; i++ {
for {
if pattern[i] == pattern[l] {
l++
break
}
if l == 0 {
break
}
l = lps[l-1]
}
lps[i] = l
}
i = 0
j = 0
for ; i < N; i++ {
for {
if pattern[j] == input[i] {
j++
if j == M {
result = append(result, i-j+1)
j = lps[j-1]
}
break
}
if j > 0 {
j = lps[j-1]
} else {
break
}
}
}
return result
}