kpm算法基本操作代码实现
时间: 2023-05-17 18:04:29 浏览: 96
并行程序设计开题知识.pdf
以下是 KMP 算法的基本操作代码实现:
```python
def kmp(text, pattern):
n = len(text)
m = len(pattern)
if m == 0:
return 0
fail = compute_fail(pattern)
j = 0
for i in range(n):
while j > 0 and pattern[j] != text[i]:
j = fail[j-1]
if pattern[j] == text[i]:
j += 1
if j == m:
return i - m + 1
return -1
def compute_fail(pattern):
m = len(pattern)
fail = [0] * m
j = 0
for i in range(1, m):
while j > 0 and pattern[j] != pattern[i]:
j = fail[j-1]
if pattern[j] == pattern[i]:
j += 1
fail[i] = j
return fail
```
这段代码实现了 KMP 算法的主要逻辑,其中 `compute_fail` 函数用于计算模式串的失配函数,`kmp` 函数用于在文本串中查找模式串。
阅读全文