您的位置:首页 > 编程语言 > Python开发

leetcode implement strStr python

2015-11-29 21:05 661 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: