-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.swift
More file actions
34 lines (30 loc) · 759 Bytes
/
Solution.swift
File metadata and controls
34 lines (30 loc) · 759 Bytes
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
/*
Implement strStr()
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*/
func strStr(_ haystack: String, _ needle: String) -> Int {
if needle.count > haystack.count {
return -1
}
if needle.count == 0 {
return 0
}
var hay = Array(haystack)
var need = Array(needle)
for i in 0..<(hay.count - need.count + 1) {
var found = true
for j in 0..<need.count {
guard i + j < hay.count else {
found = false
break
}
if hay[i + j] != need[j] {
found = false
}
}
if found {
return i
}
}
return -1
}