The Knuth-Morris-Pratt (KMP) algorithm is an efficient string searching algorithm that preprocesses the pattern to create a longest prefix-suffix (LPS) array. This allows the search process to skip characters, making it faster compared to the naive search approach.
func KMPSearch(pattern: String, text: String) {
let m = pattern.count
let n = text.count
var lps = [Int](repeating: 0, count: m)
var j = 0 // index for pattern
computeLPSArray(pattern: pattern, lps: &lps)
var i = 0 // index for text
while i < n {
if pattern[pattern.index(pattern.startIndex, offsetBy: j)] == text[text.index(text.startIndex, offsetBy: i)] {
i += 1
j += 1
}
if j == m {
print("Found pattern at index \(i - j)")
j = lps[j - 1]
} else if i < n && pattern[pattern.index(pattern.startIndex, offsetBy: j)] != text[text.index(text.startIndex, offsetBy: i)] {
if j != 0 {
j = lps[j - 1]
} else {
i += 1
}
}
}
}
func computeLPSArray(pattern: String, lps: inout [Int]) {
let m = pattern.count
var length = 0 // length of the previous longest prefix suffix
var i = 1
lps[0] = 0
while i < m {
if pattern[pattern.index(pattern.startIndex, offsetBy: i)] == pattern[pattern.index(pattern.startIndex, offsetBy: length)] {
length += 1
lps[i] = length
i += 1
} else {
if length != 0 {
length = lps[length - 1]
} else {
lps[i] = 0
i += 1
}
}
}
}
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?