是一道简单的KMP的入门题目,
只要你弄懂了,题目中的题意还是很简单,
贴出代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
char str[200005];
char pat[100005];
int next[100005];
int N,M;
void getnext()
{
int i=1,j=0;
next[1]=0;
while(i<M)
{
if(j==0||pat[i]==pat[j])
{
i++,j++;
next[i]=j;
}
else
j=next[j];
}
}
int KMP()
{
int i=1,j=0;
while(i<=2*N&&j<=M)
{
if(j==0||str[i]==pat[j])
i++,j++;
else
j=next[j];
}
if(j>M)
return 1;
return 0;
}
int main()
{
while(scanf("%s%s",str+1,pat+1)!=EOF)
{
str[0]='#';
pat[0]='#';
N=strlen(str)-1;
M=strlen(pat)-1;
if(N<M)
{
printf("no\n");
continue;
}
for(int i=1;i<=N;i++)
{
str[i+N]=str[i];
}
str[2*N+1]='\0';
getnext();
printf(KMP()?"yes\n":"no\n");
}
return 0;
}