LeetCode-28-Implement strStr() KMP模板题

来源:互联网 发布:excel视图宏数据标签 编辑:程序博客网 时间:2024/05/23 23:36

这个题暴力也能过,我用了KMP结果才打败28%,drunk

class Solution(object):    def strStr(self, haystack, needle):        """        :type haystack: str        :type needle: str        :rtype: int        """        if needle=="":return 0        Len1=len(haystack)        Len2=len(needle)        if Len2>Len1:return -1        Next=[0]*(Len2+1)        i=0        j=0        t=-1        Next[0]=-1        while j<Len2:            if t<0 or needle[j]==needle[t]:                j+=1                t+=1                Next[j]=t            else:                t=Next[t]        i=0        j=0        while i<Len1 and j<Len2:            if j<0 or haystack[i]==needle[j]:                if j+1==Len2:return i-j                i+=1                j+=1            else:                j=Next[j]        return -1


原创粉丝点击