fear(datastructure.test5): 新增实验 5

This commit is contained in:
2025-11-24 17:53:26 +08:00
parent d0acf5a36d
commit 8996daa6aa

View File

@@ -0,0 +1,119 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int nextval[20];
int BF(char a[], char b[])
{
int i = 1;
int j = 1;
while (i <= strlen(a) && j <= strlen(b))
{
// todo list 比较数组a、b里对应位置的字符
// 若匹配成功,则继续比较后续字符;
// 若匹配不成功i指针、j指针回退重新开始匹配
if (a[i - 1] == b[j - 1])
{
i++, j++;
}
else
{
i = i - j + 2;
j = 1;
}
}
if (j > strlen(b))
{
printf("BF算法匹配成功\n");
// todo list //返回和模式b中第一个字符相等的字符在主串a中的序号
return i - strlen(b);
}
else
{
printf("BF算法匹配失败\n");
return 0;
}
}
void Nextval(char b[])
{
nextval[1] = 0;
int i = 1, j = 0;
// todo list while 循环求nextval
while (i < strlen(b))
{
if (j == 0 || b[i - 1] == b[j - 1])
{
i++;
j++;
if (b[i - 1] != b[j - 1])
{
nextval[i - 1] = j;
}
else
{
nextval[i - 1] = nextval[j - 1];
}
}
else
{
j = nextval[j - 1];
}
}
}
int KMP(char a[], char b[])
{
int i = 1, j = 1, k;
Nextval(b); // 求b串中所有字符的nextval值
for (k = 1; k <= strlen(b); k++)
{
printf("nextval[%d]为:%4d\n", k, nextval[k]);
}
while (i <= strlen(a) && j <= strlen(b))
{
// todo list 比较数组a、b里对应位置的字符
// 若匹配成功,则继续比较后续字符;
// 若匹配不成功利用nextval[j]实现j指针回退重新开始匹配
if (j == 0 || a[i - 1] == b[j - 1])
{
i++;
j++;
}
else
{
j = nextval[j - 1];
}
}
if (j > strlen(b))
{
printf("KMP算法匹配成功\n");
// todo list //返回和模式b中第一个字符相等的字符在主串a中的序号
return i - strlen(b);
}
else
{
printf("KMP算法匹配失败\n");
return 0;
}
}
int main()
{
char a[100], b[20];
printf("请输入主串:\n");
scanf("%s", a);
// gets_s(a);
printf("请输入子串:\n");
scanf("%s", b);
// gets_s(b);
printf("------------------------------------\n");
int num_BF, num_KMP;
num_BF = BF(a, b);
printf("BF:子串的第一个字符在主串中的位置为:%d\n", num_BF);
printf("------------------------------------\n");
num_KMP = KMP(a, b);
printf("KMP:子串的第一个字符在主串中的位置为:%d", num_KMP);
}