KMP Failure Function Pattern Match (Go)
Match a pattern in Go text using KMP with a precomputed failure function for linear time matching.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.