Skip to content

Instantly share code, notes, and snippets.

@gtokman
Created March 13, 2021 16:09
Show Gist options
  • Save gtokman/f7a7950b6ea1263116d5c4871c272be6 to your computer and use it in GitHub Desktop.
Save gtokman/f7a7950b6ea1263116d5c4871c272be6 to your computer and use it in GitHub Desktop.
func search(needle: String, haystack: String) -> Bool {
guard needle.count <= haystack.count else {
return false
}
if needle == haystack {
return true
}
var needleIdx = needle.startIndex
var haystackIdx = haystack.startIndex
while needleIdx != needle.endIndex {
if haystackIdx == haystack.endIndex {
return false
}
if needle[needleIdx] == haystack[haystackIdx] {
needleIdx = needle.index(after: needleIdx)
}
haystackIdx = haystack.index(after: haystackIdx)
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment