题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2203
题解:要求一个串循环后是否包含另外一个串,只要将母串重复一次再进行KMP匹配,因为在重复母串的过程中,其实据已经将循环后的所有可能都列举出来了,比如串 "ABCD" 重复后为
#include <stdio.h>
#include <string.h>
#define MAXN 100001
int next[MAXN],len1,len2;
char str1[MAXN<<1],str2[MAXN];
void getNext()
{
int i=0,j=-1;
next[0]=-1;
while(i<len2)
{
if (j==-1||str2[i]==str2[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int KMP()
{
int i,j;
i=j=0;
getNext();
while(i<len1&&j<len2)
{
if(j==-1||str1[i]==str2[j])
{
i++;
j++;
}
else
j=next[j];
}
return j;
}
int main()
{
int n,i;
while (scanf("%s %s",str1,str2)!=EOF)
{
len1=strlen(str1);
len2=strlen(str2);
if(len1<len2)
{
printf("no\n");
continue;
}
for(i=0;i<len1;++i)
str1[len1+i]=str1[i];
str1[len1*2-1]='\0';
len1=len1*2-1;
n=KMP();
if(n==len2)
printf("yes\n");
else
printf("no\n");
}
return 0;
}