Created
January 19, 2020 12:41
-
-
Save spurscho/8fb74ce8d936e3bc4c22752252d8ebe3 to your computer and use it in GitHub Desktop.
28. Implement strStr()
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
class Solution { // my code got timelimted error. this is new codes | |
func strStr(_ haystack: String, _ needle: String) -> Int { | |
guard !needle.isEmpty else { return 0 } | |
guard haystack.count >= needle.count else { return -1 } | |
let distance = haystack.count - needle.count | |
for i in 0...distance { | |
let start = haystack.index(haystack.startIndex, offsetBy: i) | |
let end = haystack.index(haystack.startIndex, offsetBy: i+needle.count) | |
if haystack[start..<end] == needle { | |
return start.encodedOffset | |
} | |
} | |
return -1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the new code still gets time limited error