Leetcode #28. Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Brute Force算法,时间复杂度 O(mn)
1 class Solution(object): 2 def strStr(self, haystack, needle): 3 """ 4 :type haystack: str 5 :type needle: str 6 :rtype: int 7 """ 8 m = len(haystack) 9 n = len(needle) 10 11 if n == 0: 12 return 0 13 14 if m < n: 15 return -1 16 17 18 for i in range(m-n+1): 19 if haystack[i:i+n] == needle: 20 return i 21 22 return -1
Rabin karp算法时间复杂度可以降低到 O(mn) on average.
haystack: abcdefgh, needle: abc
needle_code = a + b*p + c*p^2 使用sliding window计算haystack_code可以节省计算量。
KMP算法也很快,但是面试一般无法完成。
1 def charToInt(c): 2 return ord(c) - ord('a') + 1 3 4 def strStrRK(haystack, needle): 5 6 m = len(haystack) 7 n = len(needle) 8 9 if n == 0: 10 return 0 11 if m < n: 12 return -1 13 14 #choose a prime number as base 15 base = 29 16 17 needle_code = 0 18 for i in range(n): 19 needle_code += charToInt(needle[i]) * base**i 20 21 22 lead = charToInt(haystack[0]) 23 for j in range(m - n + 1): 24 25 if j == 0: 26 haystack_code = 0 27 for i in range(n): 28 haystack_code += charToInt(haystack[j + i])*base**i 29 else: 30 haystack_code -= lead 31 haystack_code /= base 32 haystack_code += charToInt(haystack[j + n - 1])*base**(n-1) 33 lead = charToInt(haystack[j]) 34 35 if haystack_code == needle_code: 36 if haystack[j:j + n] == needle: 37 return j 38 39 return -1