没搞懂,先记下来
def KMP(string, pattern):
tnext = get_next(pattern)
i = 0
j = 0
while i < len(string) and j < len(pattern):
if j == -1 or string[i] == pattern[j]:
i += 1
j += 1
else:
j = tnext[j]
if j >= len(pattern):
return i - len(pattern)
else
return -1
def get_next(pattern):
tnext = []
for i in range(len(pattern)):
tnext.append(0)
tnext[0] = -1
j = 0
k = -1
while j < len(pattern)-1:
if k == -1 or pattern[j] == pattern[k]:
j += 1
k += 1
tnext[j] = k
else:
k = tnext[k]
return tnext
print KMP('efababc', 'ababc')