Skip to content

Instantly share code, notes, and snippets.

@spurscho
Created January 19, 2020 12:41
Show Gist options
  • Select an option

  • Save spurscho/8fb74ce8d936e3bc4c22752252d8ebe3 to your computer and use it in GitHub Desktop.

Select an option

Save spurscho/8fb74ce8d936e3bc4c22752252d8ebe3 to your computer and use it in GitHub Desktop.
28. Implement strStr()
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
}
}
@onebroccoli

Copy link
Copy Markdown

the new code still gets time limited error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment