LeetCode #28 Implement strStr()

LeetCode #28 Implement strStr()

Question

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Solution

Approach #1

class Solution {
    func strStr(_ haystack: String, _ needle: String) -> Int {
        if needle.isEmpty { return 0 }
        let hArr = Array(haystack.utf16)
        let nArr = Array(needle.utf16)
        if hArr.count < nArr.count { return -1 }
        for i in 0...hArr.count - nArr.count {
            for j in 0...nArr.count {
                if j == nArr.count { return i }
                if hArr[i + j] != nArr[j] { break }
            }
        }
        return -1
    }
}

Time complexity: O(m * n). m is length of haystack and n is length of needle.

Space complexity: O(m + n). UTF16 arrays (hArr and nArr) need space.

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7067126.html

posted on 2017-06-23 18:36  Silence_cnblogs  阅读(224)  评论(0编辑  收藏  举报