MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / Kmp

Function Kmp

strings/kmp/kmp.go:4–33  ·  view source on GitHub ↗

Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.

(word, text string, patternTable []int)

Source from the content-addressed store, hash-verified

2
3// Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.
4func Kmp(word, text string, patternTable []int) []int {
5 if len(word) > len(text) {
6 return nil
7 }
8
9 var (
10 i, j int
11 matches []int
12 )
13 for i+j < len(text) {
14
15 if word[j] == text[i+j] {
16 j++
17 if j == len(word) {
18 matches = append(matches, i)
19
20 i = i + j
21 j = 0
22 }
23 } else {
24 i = i + j - patternTable[j]
25 if patternTable[j] > -1 {
26 j = patternTable[j]
27 } else {
28 j = 0
29 }
30 }
31 }
32 return matches
33}
34
35// table building for kmp algorithm.
36func table(w string) []int {

Callers 1

TestKmpFunction · 0.85

Calls

no outgoing calls

Tested by 1

TestKmpFunction · 0.68