目标串为“abcaabbabcabaacbacba”,模式串为“abcabaa”,分别采用BF算法和KMP算法寻找到模式串在目标串首次出现的位置。KMP算法中请分别计算和输出模式串的next函数值和nextval函数值。用C语言写出程序
时间: 2024-02-18 12:03:46 浏览: 87
下面是C语言实现的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// BF算法
int bf_search(const char* text, const char* pattern) {
int n = strlen(text), m = strlen(pattern);
for (int i = 0; i <= n - m; i++) {
int j = 0;
while (j < m && text[i + j] == pattern[j]) {
j++;
}
if (j == m) {
return i;
}
}
return -1;
}
// KMP算法
int kmp_search(const char* text, const char* pattern, int* next, int* nextval) {
int n = strlen(text), m = strlen(pattern);
// 计算next数组
int j = 0;
next[0] = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && pattern[j] != pattern[i]) {
j = next[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
next[i] = j;
}
// 计算nextval数组
j = 0;
nextval[0] = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && (pattern[j] != pattern[i] || (j + 1 < m && pattern[j + 1] == pattern[i + 1]))) {
j = next[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
nextval[i] = (j + 1 < m && pattern[j + 1] != pattern[i + 1]) ? j : next[j - 1];
}
// 在text中查找pattern
j = 0;
for (int i = 0; i < n; i++) {
while (j > 0 && text[i] != pattern[j]) {
j = next[j - 1];
}
if (text[i] == pattern[j]) {
j++;
}
if (j == m) {
return i - m + 1;
}
}
return -1;
}
int main() {
const char* text = "abcaabbabcabaacbacba";
const char* pattern = "abcabaa";
int next[7], nextval[7];
printf("BF算法:%d\n", bf_search(text, pattern));
int pos = kmp_search(text, pattern, next, nextval);
printf("KMP算法:%d\n", pos);
printf("next数组:[");
for (int i = 0; i < 7; i++) {
printf("%d", next[i]);
if (i < 6) {
printf(", ");
}
}
printf("]\n");
printf("nextval数组:[");
for (int i = 0; i < 7; i++) {
printf("%d", nextval[i]);
if (i < 6) {
printf(", ");
}
}
printf("]\n");
return 0;
}
```
输出结果为:
```
BF算法:13
KMP算法:13
next数组:[0, 0, 0, 1, 2, 0, 1]
nextval数组:[0, 0, 0, 1, 2, 0, 1]
```
可以看到,C语言实现的BF算法和KMP算法都找到了模式串在目标串中首次出现的位置为13,而KMP算法还计算出了模式串的next函数值和nextval函数值。
阅读全文