-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathsingle-pattern-search.go
More file actions
53 lines (49 loc) · 990 Bytes
/
single-pattern-search.go
File metadata and controls
53 lines (49 loc) · 990 Bytes
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
package string
/*
import (
"fmt"
)
*/
func KMPSearch(source string, pattern string) int {
si := 0
pi := 0
nextPatternIndexArray := generateNextPatternIndexArray(pattern)
for si < len(source) && pi < len(pattern) {
if pi == -1 || ([]byte(source)[si] == []byte(pattern)[pi]) {
si++
pi++
} else {
pi = nextPatternIndexArray[pi]
}
}
if pi == len(pattern) {
return si - pi
} else {
return -1
}
}
func generateNextPatternIndexArray(pattern string) []int {
length := len(pattern)
array := make([]int, length)
array[0] = -1
prefixI := -1
suffixI := 0
for suffixI < length - 1 {
if prefixI == -1 || ([]byte(pattern)[prefixI] == []byte(pattern)[suffixI]) {
prefixI++
suffixI++
if []byte(pattern)[prefixI] != []byte(pattern)[suffixI] {
array[suffixI] = prefixI
} else {
array[suffixI] = array[prefixI]
}
} else {
prefixI = array[prefixI]
}
}
return array
}
func BMSearch(source string, pattern string) int {
//TODO
return -1
}