Created
June 5, 2022 17:07
-
-
Save derekli66/f10efa0c696fdc651991fa846b5eebc2 to your computer and use it in GitHub Desktop.
KMP string matching algorithm. Implement in Swift.
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
func buildKMP(_ pattern: String) -> [Int] { | |
let strs = Array(pattern).map { String($0) } | |
var kmp = Array(repeating: 0, count: strs.count) | |
var i = 1 | |
var j = 0 | |
while i < strs.count { | |
if strs[i] == strs[j] { | |
kmp[i] = j + 1 | |
i += 1 | |
j += 1 | |
} | |
else { | |
if j != 0 { | |
j = kmp[j - 1] | |
} | |
else { | |
i += 1 | |
} | |
} | |
} | |
return kmp | |
} | |
func contains(_ source_: String, _ pattern_: String) -> Int { | |
if pattern_.count > source_.count { return -1 } | |
let kmp = buildKMP(pattern_) | |
let pattern = Array(pattern_).map {String($0)} | |
let source = Array(source_).map {String($0)} | |
var i = 0 | |
var j = 0 | |
while i < source.count { | |
if source[i] == pattern[j] { | |
i += 1 | |
j += 1 | |
} | |
if j == pattern.count { | |
return i - j | |
} | |
else if i < source.count && source[i] != pattern[j] { | |
if j != 0 { | |
j = kmp[j - 1] | |
} | |
else { | |
i += 1 | |
} | |
} | |
} | |
return -1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment