1、应用BF算法求子串"JING"在主串"BEIJING"中的位置,测试起始位置分别为1和5的情况; 2、应用KMP算法求子串"abaabcac"在主串"acabaabaabcacaabc"中的位置,测试起始位置分别为1,10的情况,并写出子串的next[]值和nextval[]的值; 菜单选项为:0、退出;1、BF算法实现;2、KMP算法实现。
时间: 2024-04-22 11:22:02 浏览: 14
我明白了,可以为您解答。
1. BF算法实现:
当测试起始位置为1时,主串"BEIJING"中子串"JING"的位置为2;当测试起始位置为5时,主串"BEIJING"中子串"JING"的位置为-1(即不存在)。
2. KMP算法实现:
当测试起始位置为1时,主串"acabaabaabcacaabc"中子串"abaabcac"的位置为8;当测试起始位置为10时,主串"acabaabaabcacaabc"中子串"abaabcac"的位置为-1(即不存在)。
子串"abaabcac"的next[]值为:-1 0 0 1 1 2 0 1。
子串"abaabcac"的nextval[]值为:-1 0 -1 1 1 2 -1 1。
注意,这里的next[]和nextval[]值可能因为算法实现细节的不同而有所差异。
相关问题
c语言代码1、应用BF算法求子串"JING"在主串"BEIJING"中的位置,测试起始位置分别为1和5的情况; 2、应用KMP算法求子串"abaabcac"在主串"acabaabaabcacaabc"中的位置,测试起始位置分别为1,10的情况,并写出子串的next[]值和nextval[]的值; 菜单选项为:0、退出;1、BF算法实现;2、KMP算法实现。
好的,以下是C语言代码实现:
1. BF算法实现:
```c
#include <stdio.h>
#include <string.h>
int BF(char *s, char *p, int pos) {
int i = pos, j = 0;
while (i < strlen(s) && j < strlen(p)) {
if (s[i] == p[j]) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
if (j == strlen(p)) {
return i - strlen(p) + 1;
} else {
return -1;
}
}
int main() {
char s[] = "BEIJING";
char p[] = "JING";
int pos1 = 1, pos2 = 5;
int res1 = BF(s, p, pos1 - 1);
int res2 = BF(s, p, pos2 - 1);
printf("测试起始位置为%d时,子串在主串中的位置为%d\n", pos1, res1);
printf("测试起始位置为%d时,子串在主串中的位置为%d\n", pos2, res2);
return 0;
}
```
2. KMP算法实现:
```c
#include <stdio.h>
#include <string.h>
void getNext(char *p, int next[], int nextval[]) {
int i = 0, j = -1;
next[0] = -1;
nextval[0] = -1;
while (i < strlen(p)) {
if (j == -1 || p[i] == p[j]) {
i++;
j++;
next[i] = j;
if (p[i] != p[j]) {
nextval[i] = j;
} else {
nextval[i] = nextval[j];
}
} else {
j = next[j];
}
}
}
int KMP(char *s, char *p, int pos, int next[], int nextval[]) {
int i = pos, j = 0;
while (i < strlen(s) && j < strlen(p)) {
if (j == -1 || s[i] == p[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == strlen(p)) {
return i - strlen(p) + 1;
} else {
return -1;
}
}
int main() {
char s[] = "acabaabaabcacaabc";
char p[] = "abaabcac";
int pos1 = 1, pos2 = 10;
int next[strlen(p)], nextval[strlen(p)];
getNext(p, next, nextval);
int res1 = KMP(s, p, pos1 - 1, next, nextval);
int res2 = KMP(s, p, pos2 - 1, next, nextval);
printf("测试起始位置为%d时,子串在主串中的位置为%d\n", pos1, res1);
printf("测试起始位置为%d时,子串在主串中的位置为%d\n", pos2, res2);
printf("子串的next[]值为:");
for (int i = 0; i < strlen(p); i++) {
printf("%d ", next[i]);
}
printf("\n子串的nextval[]值为:");
for (int i = 0; i < strlen(p); i++) {
printf("%d ", nextval[i]);
}
printf("\n");
return 0;
}
```
使用BF算法进行匹配,并输出主串内容、子串内容以及在主串中的匹配位置
很高兴能够回答你的问题。关于你所提到的使用BF算法匹配的问题,我能够回答。
主串内容、子串内容,以及在主串中的匹配位置是在使用BF算法进行匹配时需要输出的结果。BF算法也称为暴力匹配算法,是一种简单的字符串匹配算法。其基本思路是,先将子串与主串对齐,从第一个字符开始一一进行比较,如果发现有不相等的字符,则将子串向右移动一位,重新对齐,再进行比较,直到子串与主串完全匹配或者主串遍历完毕。
具体的实现方法可以参考以下步骤:
1.遍历主串,将子串首字符与主串相应位置的字符进行比较;
2.如果匹配成功,则继续比较子串的后续字符,直至子串匹配完成;
3.如果匹配失败,则将子串向右移动一位,重新与主串相对应位置的字符进行比较;
4.重复步骤2~3直至匹配成功或者主串遍历完毕。
匹配成功后,可以输出主串内容、子串内容以及在主串中的匹配位置。
希望我的回答能够对你有所帮助,如果你还有其他问题,欢迎随时提出。