Created
June 14, 2022 15:46
-
-
Save derekli66/c2d53fa58cd8bd6fad43a5dfb53ba6a9 to your computer and use it in GitHub Desktop.
Implement KMPMatch and KMPSearch function to check if pattern exists and the index of matched pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func computeLPS(_ pattern: String) -> [Int] { | |
let array = Array(pattern).map{String($0)} | |
var i = 1 | |
var j = 0 | |
var lps = Array(repeating: 0, count: array.count) | |
while i < array.count { | |
if array[j] == array[i] { | |
j += 1 | |
lps[i] = j | |
i += 1 | |
} | |
else { | |
if j != 0 { | |
j = lps[j - 1] | |
} | |
else { | |
i += 1 | |
} | |
} | |
} | |
return lps | |
} | |
func KMPMatch(_ str_: String, _ pattern_: String) -> Bool { | |
let lps = computeLPS(pattern_) | |
let str = Array(str_).map{ String($0) } | |
let pattern = Array(pattern_).map{ String($0) } | |
var i = 0 | |
var j = 0 | |
var contains = false | |
while i < str.count { | |
if str[i] == pattern[j] { | |
i += 1 | |
j += 1 | |
} | |
if j == pattern.count { | |
contains = true | |
j = 0 | |
} | |
if i < str.count && str[i] != pattern[j] { | |
if j != 0 { | |
j = lps[j - 1] | |
} | |
else { | |
i += 1 | |
} | |
} | |
} | |
return contains | |
} | |
func KMPSearch(_ str_: String, _ pattern_: String) -> [Int] { | |
let lps = computeLPS(pattern_) | |
let str = Array(str_).map{ String($0) } | |
let pattern = Array(pattern_).map{ String($0) } | |
var i = 0 | |
var j = 0 | |
var result = [Int]() | |
while i < str.count { | |
if str[i] == pattern[j] { | |
i += 1 | |
j += 1 | |
} | |
if j == pattern.count { | |
result.append(i - j) | |
j = 0 | |
} | |
if i < str.count && str[i] != pattern[j] { | |
if j != 0 { | |
j = lps[j - 1] | |
} | |
else { | |
i += 1 | |
} | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment