How do I implement KMP string search in Swift?

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.

Swift Implementation of KMP Algorithm

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 } } } }

Swift KMP Algorithm String Search Algorithm Implementation