Implement strStr().html
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.swift
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.app
Space complexity: O(m + n). UTF16 arrays (hArr and nArr) need space.spa
轉載請註明出處:http://www.cnblogs.com/silence-cnblogs/p/7067126.htmlcode