KMP Failure Function Pattern Match (Go)

Match a pattern in Go text using KMP with a precomputed failure function for linear time matching.

GoData Fetching

Code

gosnippet
12 lines
package main

func kmpSearch(text, pattern string) []int {
	n, m := len(text), len(pattern)
	if m == 0 { return []int{0} }
	fail := make([]int, m)
	j := 0
	for i := 1; i < m; i++ { for j > 0 && pattern[i] != pattern[j] { j = fail[j-1] }; if pattern[i] == pattern[j] { j++ }; fail[i] = j }
	var result []int; j = 0
	for i := 0; i < n; i++ { for j > 0 && text[i] != pattern[j] { j = fail[j-1] }; if text[i] == pattern[j] { j++ }; if j == m { result = append(result, i-m+1); j = fail[j-1] } }
	return result
}

Walking through the source

Count the function kmpSearch as the entire surface area of KMP Failure Function Pattern Match (Go).

Repetition is confined to for i := 1; i < m; i++ { for j > 0 && pattern[i] != pattern[j] { j = fail[j-1] }; if pattern[i] =… — the rest of the file is straight-line.

Applying it

Entry signature: func kmpSearch(text, pattern string) []int

Statements that matter

if m == 0 { return []int{0} }
fail := make([]int, m)

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `kmpSearch` at load time.