Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save derekli66/6b5ddae2c10c5ec9412cd90c10ca3040 to your computer and use it in GitHub Desktop.
Save derekli66/6b5ddae2c10c5ec9412cd90c10ca3040 to your computer and use it in GitHub Desktop.
The solution to LeetCode problem, Check If a Word Occurs As a Prefix of Any Word in a Sentence. https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
class Solution {
func isPrefixOfWord(_ sentence: String, _ searchWord: String) -> Int {
let sentence = " " + sentence
let searchWord = " " + searchWord
let index = contains(sentence, searchWord)
let strs = Array(sentence).map{String($0)}
var count = 0
for idx in 0..<strs.count {
if strs[idx] == " " {
count += 1
if idx == index { return count }
}
}
return -1
}
private 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
}
private 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