-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementStrStr.swift
More file actions
40 lines (35 loc) · 1.04 KB
/
ImplementStrStr.swift
File metadata and controls
40 lines (35 loc) · 1.04 KB
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
//
// Implement strStr.swift
//
// Created by PixelShi on 2017/2/11.
// Copyright © 2017年 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Solution {
func strStr(_ haystack: String, _ needle: String) -> Int {
let hChars = Array(haystack.characters)
let nChars = Array(needle.characters)
guard hChars.count >= nChars.count else {
return -1
}
guard nChars.count != 0 else {
return 0
}
for i in 0...(hChars.count - nChars.count) {
// 找到第一个相等的
if hChars[i] == nChars[0] {
for j in 0..<nChars.count {
// 如果子串某一位和父串不相等,退出循环
if hChars[i+j] != nChars[j] {
break
}
// 找到子串匹配父串
if j + 1 == nChars.count {
return i
}
}
}
}
return -1
}
}