Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[String] Add a solution to Implement strStr #303

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions String/StrStr.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class StrStr {
func strStr(_ haystack: String, _ needle: String) -> Int {
let hChars = Array(haystack.characters), nChars = Array(needle.characters)
let hChars = Array(haystack), nChars = Array(needle)
let hLen = hChars.count, nLen = nChars.count

guard hLen >= nLen else {
Expand All @@ -31,4 +31,32 @@ class StrStr {

return -1
}
}
}



class StrStrWithSubstring {
func strStr(_ haystack: String, _ needle: String) -> Int {
guard needle.count > 0 else {
return 0
}

guard haystack.count >= needle.count else {
return -1
}

let shiftIndex = needle.count - 1
let maxLowerIndex = haystack.count - needle.count

for lowerIndex in 0...maxLowerIndex {
let lowerBound: String.Index = haystack.index(haystack.startIndex, offsetBy: lowerIndex)
let upperBound: String.Index = haystack.index(haystack.startIndex, offsetBy: lowerIndex + shiftIndex)

if haystack[lowerBound...upperBound] == needle {
return lowerIndex
}
}

return -1
}
}