The Knuth-Morris-Pratt (KMP) algorithm is an efficient string searching algorithm that searches for occurrences of a word within a main text string. It preprocesses the pattern to create a partial match table (also known as the "prefix" table) that helps in skipping unnecessary comparisons.
Go, KMP String Search, String Matching, Algorithm, Pattern Matching
This example implements the KMP algorithm in Go, illustrating how to perform a substring search efficiently.
package main
import "fmt"
// KMPSearch implements the KMP string search algorithm.
func KMPSearch(pattern, text string) []int {
m := len(pattern)
n := len(text)
lps := computeLPSArray(pattern)
indices := []int{}
i, j := 0, 0
for i < n {
if pattern[j] == text[i] {
i++
j++
}
if j == m {
indices = append(indices, i-j)
j = lps[j-1]
} else if i < n && pattern[j] != text[i] {
if j != 0 {
j = lps[j-1]
} else {
i++
}
}
}
return indices
}
// computeLPSArray computes the longest prefix which is also suffix array for KMP.
func computeLPSArray(pattern string) []int {
length := 0
lps := make([]int, len(pattern))
lps[0] = 0
i := 1
for i < len(pattern) {
if pattern[i] == pattern[length] {
length++
lps[i] = length
i++
} else {
if length != 0 {
length = lps[length-1]
} else {
lps[i] = 0
i++
}
}
}
return lps
}
func main() {
text := "ABABDABACDABABCABAB"
pattern := "ABABCABAB"
result := KMPSearch(pattern, text)
fmt.Println("Pattern found at indices:", result)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?