要实现KMP算法首先要解决的就是关于next数组的求解方法。KMP算法的精髓便在于这一点上。可是严蔚敏版的数据结构在这一点上解释的不利于理解。下面是一个来自B站的视频,大家可以作为先修知识理解KMP算法的工作原理以及手动求解next数组的方法。
https://www.bilibili.com/video/BV1jb411V78H?from=search&seid=975091333872042622
理解完成上面的知识,下面就是如何编程实现对子串next数组的求解。这里需要注意的是,**根据严蔚敏版的数据结构默认字符串的存取是从1位置开始,而不是从0位置开始。**我们开始重点讲解next数组的编程原理:
弄清上面的next数组的求解,后续的代码编译问题就迎刃而解了:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 255
typedef struct
{
char str[MAX+1];
int length;
}SSteing;
void get_next(SSteing T,int next[]);
int KMP(SSteing S,SSteing T,int next[]);
int main(void)
{
SSteing S,T;
char a[MAX+1],b[MAX+1];
int next[MAX+1];
printf("请输入主串:");
scanf("%s",a);
printf("请输入字串:");
scanf("%s",b);
S.length = strlen(a);
T.length = strlen(b);
for(int i = 1;i < S.length+1;i++)
{
S.str[i] = a[i-1];
}
for(int i = 1;i < T.length+1;i++)
{
T.str[i] = b[i-1];
}
get_next(T,next);
KMP(S,T,next);
if(KMP(S,T,next))
{
printf("匹配成功!起始位置为:%d\n",KMP(S,T,next));
}
else
{
printf("匹配失败!\n");
}
system("pause");
return 0;
}
void get_next(SSteing T,int next[])
{
int j = 1,t = 0;
next[1] = 0;
while (j < T.length)
{
if(t == 0 || T.str[j] == T.str[t])
{
j++;
t++;
next[j] = t;
}
else
{
t = next[t];
}
}
printf("该字串的next数组为:");
for(int i = 1;i < T.length + 1;i++)
{
printf("%d ",next[i]);
}
printf("\n");
}
int KMP(SSteing S,SSteing T,int next[])
{
int i = 1,j = 1;
while (i <= S.length && j <= T.length)
{
if(j == 0 || S.str[i] == T.str[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if(j > T.length)
{
return i - T.length;
}
else
{
return 0;
}
}
如果您疑问或是见解欢迎私聊我或者邮箱1308269670@qq.com联系我。