Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路:模式匹配问题,即在原始串中寻找第一个匹配目标串的位置。利用KMP算法,分两步,1.求next数组 2.根据next数组寻找目标串匹配位置。
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:return 0
i=-1;j=0
next = [-1]*len(needle)
while j<len(needle)-1:
if i==-1 or needle[i]==needle[j]:
i,j = i+1,j+1
next[j] = i
else:
i = next[i]
i=0;j=0
while i<len(haystack) and j<len(needle):
if j==-1 or haystack[i]==needle[j]:
i,j = i+1,j+1
else:
j = next[j]
if j==len(needle):
return i-j
return -1