'''starryj'''
import time
def kmp_next(pattern):
"""得到部分匹配表
A B C D A B D
0 0 0 0 1 2 0"""
next = [int(0)]
for i in range(1, len(pattern)):
pa = pattern[:i + 1]
if pa[0] == pa[-1]:
x = 1
else:
x = 0
for p in range(1, i):
if pa[:i + 1 - p] == pa[p:]:
x = i + 1 - p
else:
continue
next.append(x)
return next
strings = 'ABC ABCDAB ABCDABCDABDE'
pattern = 'abcabcacab'
# strings = 'hello world!'
# pattern = 'world'
print(kmp_next(pattern))
def matching_kmp(strings, pattern, index):
s = len(strings)
p = len(pattern)
j = 0
i = 0
while j < s and i < p:
if strings[j] == pattern[i]:
j, i = j + 1, i + 1
elif strings[j] != pattern[0]:
j += 1
else:
if index[i - 1] != 0:
j -= index[i - 1]
else:
j += 1
i = index[i]
if i == p:
return j - i
else:
return '没有匹配的'
t1 = time.time()
index = kmp_next(pattern)
t = matching_kmp(strings, pattern, index)
print(t)
print(time.time() - t1)
python KMP
最新推荐文章于 2024-08-12 08:50:45 发布