相关介绍在下面:
- https://blog.csdn.net/yutianzuijin/article/details/11954939
- http://www.cnblogs.com/dolphin0520/archive/2011/08/24/2151846.html
实际上,最先看的是2
,但并描述没那么清晰,1
上的图描述易于理解。这里保存一下。注释见图注。
def genNext(s, nextTab=None, idx=0):
assert idx>=0, idx
if nextTab is None:
nextTab = [0 for i in s]
if idx==len(nextTab):
return nextTab
if idx ==0:
nextTab[idx] = -1
# fill the idx-th element...
else:
if s[nextTab[idx-1]+1] == s[idx]:
nextTab[idx] = nextTab[idx-1] +1
else:
nextTab[idx] = 0
return genNext(s,nextTab, idx+1)
s='ababcababa'
p='ababa'
print s
print p
print genNext(p)
def searchPat(s,p):
nextTab = genNext(p)
j=0
i=0
while True:
if s[i]==p[j]:
j+=1
i+=1
elif nextTab[j] >=0:
j=nextTab[j]
elif nextTab[j]==-1:
i += 1
j = 0
# print i,j
if j==len(p):
return i-j
return -1
print searchPat(s,p)