forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
implementStrStr().swift
83 lines (69 loc) · 1.95 KB
/
implementStrStr().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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//
// implementStrStr().swift
//
//
// Created by Dong, Anyuan (133) on 2019/4/5.
//
import Foundation
/*
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
https://leetcode.com/problems/implement-strstr/description/
*/
/*
class Solution {
func strStr(_ haystack: String, _ needle: String) -> Int {
guard !needle.isEmpty else { return 0 }
if haystack == needle {return 0}
if haystack.count < needle.count {return -1}
for i in 0 ... (haystack.count - needle.count) {
let len = i + needle.count
for j in i ..< len {
let hc = haystack[haystack.index(haystack.startIndex, offsetBy: j)]
let nc = needle[needle.index(needle.startIndex, offsetBy: j - i)]
if hc != nc { break }
print(j)
if j == (len - 1) { return i }
}
}
return -1
}
}
*/
class Solution {
func strStr(_ haystack: String, _ needle: String) -> Int {
guard needle.count > 0 else {
return 0
}
if haystack == needle {return 0}
if haystack.count < needle.count {return -1}
let arrayHayStack = Array(haystack).map { c in
return String(c)
}
let arrayNeedle = Array(needle).map { c in
return String(c)
}
for i in 0 ..< arrayHayStack.count {
if arrayHayStack.count - i < arrayNeedle.count {
break
}
let c = arrayHayStack[i]
let n = arrayNeedle[0]
var success = false
if c == n {
success = true
for j in 1 ..< arrayNeedle.count {
let n = arrayNeedle[j]
let c = arrayHayStack[i + j]
if n != c {
success = false
break
}
}
}
if success {
return i
}
}
return -1
}
}