这个题暴力也能过,我用了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
本文介绍了一种字符串匹配算法——KMP算法,并通过实例演示了如何使用该算法解决特定问题。文章首先给出了KMP算法的基本思想,接着通过Python代码展示了具体的实现过程,最后讨论了算法的时间复杂度。
706

被折叠的 条评论
为什么被折叠?



