forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StrStr.swift
37 lines (31 loc) · 970 Bytes
/
StrStr.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Question Link: https://leetcode.com/problems/implement-strstr/
* Primary idea: Iterate two strings
* Time Complexity: O(nm), Space Complexity: O(n)
*/
class StrStr {
func strStr(haystack: String, _ needle: String) -> Int {
var hChars = [Character](haystack.characters)
var nChars = [Character](needle.characters)
guard hChars.count >= nChars.count else {
return -1
}
if nChars.count == 0 {
return 0
}
for i in 0 ... hChars.count - nChars.count {
guard hChars[i] == nChars[0] else {
continue
}
for j in 0 ..< nChars.count {
guard hChars[i + j] == nChars[j] else {
break
}
if j == nChars.count - 1 {
return i
}
}
}
return -1
}
}