forked from akgmage/data-structures-and-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.go
More file actions
74 lines (62 loc) · 1.22 KB
/
Copy pathKMP.go
File metadata and controls
74 lines (62 loc) · 1.22 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
)
// computeLPSArray computes the Longest Prefix Suffix (LPS) array for the given pattern.
func computeLPSArray(pattern string) []int {
length := len(pattern)
lps := make([]int, length)
lps[0] = 0
j := 0
for i := 1; i < length; {
if pattern[i] == pattern[j] {
j++
lps[i] = j
i++
} else {
if j != 0 {
j = lps[j-1]
} else {
lps[i] = 0
i++
}
}
}
return lps
}
// KMPSearch searches for occurrences of the pattern within the given text using the KMP algorithm.
func KMPSearch(text, pattern string) []int {
n := len(text)
m := len(pattern)
lps := computeLPSArray(pattern)
i := 0 // Index for text
j := 0 // Index for pattern
positions := make([]int, 0)
for i < n {
if pattern[j] == text[i] {
i++
j++
}
if j == m {
positions = append(positions, i-j)
j = lps[j-1]
} else if i < n && pattern[j] != text[i] {
if j != 0 {
j = lps[j-1]
} else {
i++
}
}
}
return positions
}
func main() {
text := "ABABDABACDABABCABAB"
pattern := "ABABCABAB"
positions := KMPSearch(text, pattern)
if len(positions) == 0 {
fmt.Println("Pattern not found in the text.")
} else {
fmt.Printf("Pattern found at positions: %v\n", positions)
}
}