Files
studycode/datastructure/2025301205+施光甲+实验五.cpp
2025-12-03 23:08:39 +08:00

115 lines
2.5 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#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里对应位置的字符
if (a[i - 1] == b[j - 1]) {
// 若匹配成功,则继续比较后续字符;
i++;
j++;
} else {
// 若匹配不成功i指针、j指针回退重新开始匹配
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] = j;
} else {
nextval[i] = nextval[j];
}
} else {
j = nextval[j];
}
}
}
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里对应位置的字符
if (j == 0 || a[i - 1] == b[j - 1]) {
// 若匹配成功,则继续比较后续字符;
i++;
j++;
} else {
// 若匹配不成功利用nextval[j]实现j指针回退重新开始匹配
j = nextval[j];
}
}
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);
return 0;
}