forked from lexrus/LeetCode.swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path28.swift
57 lines (41 loc) · 1.35 KB
/
28.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
//
// StrStr.swift
// StrStr
//
// Created by Lex Tang on 5/4/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.
*/
import Foundation
import XCTest
// Brute Force
// Time complexity:O(mn), Space complexity: O(1)
func strStr0(haystack: String, needle: String) -> Int {
let m = haystack.characters.count, n = needle.characters.count
if n > 0 {
for var i = 0, j = 0; i < m - n; ++i {
for ; j < n && haystack[i + j] == needle[j]; ++j {}
if j == n {
return i
}
}
}
return -1
}
// TODO: KMP
// TODO: Boyer Moore
// TODO: Rabin Karp
class StrStrTest: XCTestCase {
func testStrStr() {
XCTAssertEqual(strStr0("abcdefg", needle: "bcd"), 1, "")
XCTAssertEqual(strStr0("aaa", needle: "a"), 0, "")
XCTAssertEqual(strStr0("abcdefg", needle: ""), -1, "")
XCTAssertEqual(strStr0("", needle: ""), -1, "")
XCTAssertEqual(strStr0("a", needle: "adfasdfasf"), -1, "")
}
}