-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy path28_ImplementStrStr.swift
More file actions
40 lines (37 loc) · 930 Bytes
/
Copy path28_ImplementStrStr.swift
File metadata and controls
40 lines (37 loc) · 930 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
34
35
36
37
38
39
40
//
// 28_ImplementStrStr.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-08-11.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:28 Implement strStr
URL: https://leetcode.com/problems/implement-strstr/
Space: O(n)
Time: O(mn)
*/
class ImplementStrStr_Solution {
func strStr(_ haystack: String, _ needle: String) -> Int {
let longCharacters = Array(haystack.characters)
let shortCharacters = Array(needle.characters)
// NOTE: First time I missed this guard.
guard longCharacters.count >= shortCharacters.count else {
return -1
}
for i in 0...(longCharacters.count - shortCharacters.count) {
var found = true
for j in 0..<shortCharacters.count {
if longCharacters[i + j] != shortCharacters[j] {
found = false
break
}
}
if found {
return i
}
}
return -1
}
}