#include<stdio.h>
#include<string.h>
void getNext(char s[],int len,int next[])
{
next[0]=-1;
int j=next[0];
for(int i=1; i<len; i++)
{
while(j!=-1&&s[i]!=s[j+1])
j=next[j]; // 退而求其次,从上一个头尾相同的字串中出筛选更小的字串
if(s[i]==s[j+1]) // j=M; 原来是M……M; 如果现在满足Mc……Mc,则next[i]=j+1;
{
next[i]=j+1; //j可能不是-1,也有可能是
j++;
}
else //j==-1&&s[i]!=s[j+1] 没有满足条件的
{
next[i]=j;
}
}
}
bool KMP(char text[],char pattern[],int next[])
{
int n=strlen(text),m=strlen(pattern);
getNext(pattern,m,next);
int j=-1;
for(int i=0; i<n; i++)
{
while(j!=-1&&text[i]!=pattern[j+1])
j=next[j];
if(text[i]==pattern[j+1])
{
j++;
}
if(j==m-1)
return true;
}
return false;
}
int main()
{
char text[100],pattern[100];
int next[100]= {0};
gets(text);
gets(pattern);
/*printf("%s %d %d\n",s,strlen(s),sizeof(s)/sizeof(char));
if(KMP(text,pattern,next))
printf("%s is a substring of %s",pattern,text);
*/
char s[2][10]={"is not","is"};
printf("%s %s a substring of %s",pattern,s[KMP(text,pattern,next)],text);
return 0;
}
KMP算法求最长回文串
最新推荐文章于 2023-03-23 17:40:06 发布