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

 

posted @ 2015-11-29 21:05  hao.ma  阅读(156)  评论(0编辑  收藏  举报