模式匹配之kmp算法
b站视频:https://www.bilibili.com/video/av11866460/
https://www.bilibili.com/video/av16828557/?spm_id_from=333.788.videocard.1
# 找到模式的prefix_table
def prefix_table(pattern, prefix, n):
prefix[0] = 0
length = 0
i = 1
while i < n:
if pattern[i] == pattern[length]:
length += 1
prefix[i] = length
i += 1
else:
if length > 0:
length = prefix[length - 1]
else:
prefix[i] = length
i += 1
return prefix
# 移动prefix_table以便kmp算法的匹配
def move_prefix_table(prefix, n):
i = n - 1
while i > 0:
prefix[i] = prefix[i - 1]
i -= 1
prefix[0] = -1
return prefix
# kmp算法实现
def kmp_search(text, pattern):
n = len(pattern)
prefix = [0 for _ in range(n)]
prefix = prefix_table(pattern, prefix, n)
prefix = move_prefix_table(prefix, n)
m = len(text)
i = 0
j = 0
while i < m:
if j == n - 1 and text[i] == pattern[j]:
print(f"Found pattern at {i - j}")
j = prefix[j]
if text[i] == pattern[j]:
i += 1
j += 1
else:
j = prefix[j]
if j == -1:
i += 1
j += 1
if __name__ == '__main__':
pattern = 'ABABCABAA'
text = 'ABACABABCABAABABCAB'
kmp_search(text, pattern)
# Found pattern at 4