-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp.go
More file actions
57 lines (48 loc) · 1.2 KB
/
Copy pathkmp.go
File metadata and controls
57 lines (48 loc) · 1.2 KB
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
package main
import "fmt"
func calculateLps(part string) []int {
lps := make([]int, len(part))
i,j := 1,0
for ; i < len(part) ; {
if part[i] == part[j] {
lps[i] = lps[j] + 1
i +=1
j +=1
} else if j == 0 {
lps[i] = 0
i += 1
} else {
j = lps[j-1]
}
}
return lps
}
func kmp(s string, part string) []int {
matches := make([]int,0)
i,j := 0,0
lps := calculateLps(part)
for ; i < len(s) ; {
if s[i] == part[j]{
i += 1
j += 1
if j == len(part) {
idx := i - len(part)
matches = append(matches, idx)
j = lps[j-1]
}
} else if lps[j] == 0 {
i += 1
} else {
j = lps[j-1]
}
}
return matches
}
func main() {
s := "kpygkivtlqoocskpygkpygkivtlqoocssnextkqzjpycbylkaondskivtlqoocssnextkqzjpycbylkaondssnextkqzjpycbylkaondshijzgaovndkjiiuwjtcpdpbkrfsi"
part := "kpygkivtlqoocssnextkqzjpycbylkaonds"
lps := calculateLps(part)
fmt.Println("lps=",lps)
matches := kmp(s, part)
fmt.Println("matches=", matches)
}