KMP 算法详解:高效字符串匹配的利器
KMP 算法(Knuth-Morris-Pratt 算法)是一种用于字符串匹配的算法。它通过利用已经匹配过的部分来避免不必要的比较,从而提高匹配效率。下面是一个使用 KMP 算法进行字符串匹配的示例代码:
def kmp_search(text, pattern):
n = len(text)
m = len(pattern)
# 构建部分匹配表
lps = [0] * m
compute_lps_array(pattern, m, lps)
result = []
i = 0 # 文本指针
j = 0 # 模式指针
while i < n:
if pattern[j] == text[i]:
i += 1
j += 1
if j == m:
result.append(i - j)
j = lps[j - 1] # 继续寻找下一个匹配的位置
else:
if j != 0:
j = lps[j - 1]
else:
i += 1
return result
def compute_lps_array(pattern, m, lps):
length = 0
i = 1
while i < m:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
# 示例用法
text = 'I love xiaomi, I often visit mi.com to buy phone'
pattern = 'xiaomi'
result = kmp_search(text, pattern)
print('共找到 %d 个目标序列' % len(result))
print('目标序列的位置:', result)
在上述示例代码中,我们定义了kmp_search函数用于执行 KMP 算法的字符串匹配。compute_lps_array函数用于构建部分匹配表(即最长公共前后缀长度表)。最后,我们给出了一个示例用法,使用 KMP 算法在文本中查找目标序列。
请注意,上述代码仅为示例,您可以根据实际情况进行调整和拓展。同时,如果您需要匹配多个目标序列,可以在循环中多次调用kmp_search函数。
希望这能帮助到您编写 KMP 算法的代码!如有任何疑问,请随时提问。
原文地址: https://www.cveoy.top/t/topic/XM7 著作权归作者所有。请勿转载和采集!