一.问题描述
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
二.代码编写
最基本的想法就是,为两个字符串指定两个指针,相同则两个指针后移,不同则子串回退到0,母串往前回退i-j+1个字符。显然,时间复杂度是O(mn),代码如下:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
len_hay = len(haystack)
len_nee = len(needle)
i = 0 # pointer for haystack
j = 0 # pointer for needle
while i < len_hay and j < len_nee:
if haystack[i] == needle[j]:
i += 1
j += 1
else:
i = i - j + 1
j = 0
if j == len_nee:
return i - len_nee
else:
return -1
三.算法优化
以尽量减少冗余计算来看待上述问题会发现,每次遇到不相同的字符时,两个子串均向前回退,显然造成了冗余的计算量,有没有办法巧妙地记住已经比较过的规律,使每次回退的字符数减少呢?这就是KMP算法的基本思想。
KMP算法通过next()数组,可以得到每次移动的长度,其时间复杂度为O(m+n)