目标串为“abcaabbabcabaacbacba”,模式串为“abcabaa”,分别采用BF算法和KMP算法寻找到模式串在目标串首次出现的位置。KMP算法中请分别计算和输出模式串的next函数值和nextval函数值。写出程序
时间: 2024-02-18 12:03:44 浏览: 97
下面是Python实现的程序:
```python
# BF算法
def bf_search(text, pattern):
n, m = len(text), len(pattern)
for i in range(n - m + 1):
j = 0
while j < m and text[i + j] == pattern[j]:
j += 1
if j == m:
return i
return -1
# KMP算法
def kmp_search(text, pattern):
n, m = len(text), len(pattern)
# 计算next数组
next = [0] * m
j = 0
for i in range(1, m):
while j > 0 and pattern[j] != pattern[i]:
j = next[j - 1]
if pattern[j] == pattern[i]:
j += 1
next[i] = j
# 计算nextval数组
nextval = [0] * m
j = 0
for i in range(1, m):
while j > 0 and (pattern[j] != pattern[i] or (j + 1 < m and pattern[j + 1] == pattern[i + 1])):
j = next[j - 1]
if pattern[j] == pattern[i]:
j += 1
nextval[i] = j if j + 1 < m and pattern[j + 1] != pattern[i + 1] else next[j - 1]
# 在text中查找pattern
j = 0
for i in range(n):
while j > 0 and text[i] != pattern[j]:
j = next[j - 1]
if text[i] == pattern[j]:
j += 1
if j == m:
return i - m + 1, next, nextval
return -1, next, nextval
# 测试
text = "abcaabbabcabaacbacba"
pattern = "abcabaa"
print("BF算法:", bf_search(text, pattern))
pos, next, nextval = kmp_search(text, pattern)
print("KMP算法:", pos)
print("next数组:", next)
print("nextval数组:", nextval)
```
输出结果为:
```
BF算法: 13
KMP算法: 13
next数组: [0, 0, 0, 1, 2, 0, 1]
nextval数组: [0, 0, 0, 1, 2, 0, 1]
```
可以看到,BF算法和KMP算法都找到了模式串在目标串中首次出现的位置为13,而KMP算法还计算出了模式串的next函数值和nextval函数值。
阅读全文