📅  最后修改于: 2023-12-03 15:11:17.589000             🧑  作者: Mango
Boyer Moore算法是一种常用的字符串匹配算法,它可以在较短时间内在一个文本串中查找一个模式串是否出现,且效率比较高。其基本思想是从模式串(T)末尾开始匹配,并在匹配失败时根据已匹配的字符决定移动模式串(T)的位置,从而达到快速匹配的目的。
def boyer_moore_search(text, pattern):
last_occurrence = {}
for i, char in enumerate(pattern):
last_occurrence[char] = i
n, m = len(text), len(pattern)
i = m - 1
if i > n - 1:
return -1
j = m - 1
while i < n:
if text[i] == pattern[j]:
if j == 0:
return i
else:
i -= 1
j -= 1
else:
if text[i] not in last_occurrence:
shift = j + 1
else:
shift = j - last_occurrence[text[i]]
i += m - min(j, 1 + last_occurrence.get(text[i], -1))
j = m - 1
return -1
Boyer Moore算法常用于文本编辑器中的查找操作中,以及计算机防病毒程序中的病毒查找操作中,还可以用于字符串比对、数据压缩、数据加密等领域。