请编程实现(a) BF(Brute Force)算法 和 (b) KMP算法来作字符串模式匹配应用。 说明:分别输入文本(Text)字符串和模式(Pattern)字符串,将其查找匹配结果显示出来。,结果如下图:
时间: 2024-10-19 15:03:57 浏览: 30
在Python中,我们可以分别使用BF(Brute Force)和KMP(Knuth-Morris-Pratt)算法来实现字符串模式匹配。以下是简单的示例代码:
**Brute Force(暴力搜索)算法:**
```python
def brute_force(text, pattern):
for i in range(len(text) - len(pattern) + 1): # 遍历所有可能的位置
match = True
for j in range(len(pattern)): # 检查每个字符是否匹配
if text[i+j] != pattern[j]:
match = False
break
if match:
print(f"Pattern found at index {i}")
```
**KMP算法:**
```python
def compute_prefix_function(pattern):
prefix_function = [0]
j = 0
for i in range(1, len(pattern)):
while j > 0 and pattern[i] != pattern[j]:
j = prefix_function[j-1]
if pattern[i] == pattern[j]:
j += 1
prefix_function.append(j)
return prefix_function
def kmp_search(text, pattern):
prefix_function = compute_prefix_function(pattern)
i = j = 0
while i < len(text):
if text[i] == pattern[j]:
i += 1
j += 1
elif j > 0:
j = prefix_function[j-1]
else:
i += 1
if j == len(pattern):
print(f"Pattern found at index {i-len(pattern)}")
j = prefix_function[j]
text = "Hello, world! This is a test string."
pattern = "test"
brute_force(text, pattern)
kmp_search(text, pattern)
```
在这个例子中,BF算法会遍历整个文本来查找模式,而KMP算法利用了前缀函数提前跳过不需要检查的部分,提高了效率。
阅读全文