标签:div imp lead bcd style prime strstr char nbsp
Brute Force算法,时间复杂度 O(mn)
1 def strStr(haystack, needle): 2 m = len(haystack) 3 n = len(needle) 4 5 if n == 0: 6 return 0 7 if m < n: 8 return -1 9 10 for i in range(m - n - 1): 11 for j in range(n): 12 if haystack[i + j] != needle[j]: 13 break 14 elif j == n - 1: 15 return i 16 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
Leetcode #28. Implement strStr()
标签:div imp lead bcd style prime strstr char nbsp
原文地址:http://www.cnblogs.com/lettuan/p/6105954.html