您的位置:首页 > 其它

LeetCode #28 Implement strStr()

2017-06-23 18:36 381 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: