leetcode implement strStr python

#kmp 
class
Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if len(haystack) <= 0 and len(needle)<=0: return 0 arrNext=self.getNext(needle) i=0 j=0 intHLen=len(haystack) intNLen=len(needle) while i < intHLen and j < intNLen: if j==-1 or haystack[i] == needle[j]: i+=1 j+=1 else: j=arrNext[j] if j == intNLen: return i-j else: return -1 def getNext(self,needle): arrNext=dict() arrNext[0]=-1 k=-1 j=0 intLen=len(needle) while j < intLen: if k==-1 or needle[k] == needle[j]: k+=1 j+=1 arrNext[j]=k else: k=arrNext[k] return arrNext
原文地址:https://www.cnblogs.com/allenhaozi/p/5005456.html