亲和串
时间限制:1000 ms | 内存限制:65535 KB
难度:3
描述
最近zyc遇到了一个很棘手的问题:判断亲和串,以前判断亲和串的时候直接可以看出来,但现在不同了,现在给出的两字符串都非常的大,看的zyc头都晕了。于是zyc希望大家能帮他想一个办法来快速判断亲和串。亲和串定义:给定两个字符串s1和s2,如果能通过s1循环移动,使s2包含在s1中,那么我们就说s2是s1的亲和串。
输入
本题有多组测试数据,每组数据的第一行包含输入字符串s1,第二行包含输入字符串s2,s1与s2的长度均小于100000。
输出
如果s2是s1的亲和串,则输出"yes",反之,输出"no"。每组测试的输出占一行。
样例输入
AABCD
CDAA
ASD
ASDF
样例输出
yes
no
代码1:基本思路,但是会超时
#include<stdio.h>
#include<string.h>
int main(void)
{
char str[2000],s1[1000],s2[2000];
while(scanf("%s%s",s1,s2)!=EOF)
{
strcpy(str,s1);
strcat(str,s1);
int flag=0;
for(int j=0;j<strlen(str);j++)
{
int i=0,k=j;
while(str[k]!='\0'&&s2[i]!='\0'&&str[k]==s2[i])
{
i++;
k++;
}
if(i==strlen(s2))
{
flag=1;
break;
}
}
if(flag==1)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
return 0;
}
代码2: KMP算法
#include<stdio.h>
#include<string.h>
#define N 100005
char s[2*N];
char s1[N];
char s2[N];
int next[N];
int len1,len2,len;
void get_next()
{
int i=0,j=-1;
next[0]=-1;
while(i<len2)
{
if(j==-1||s2[i]==s2[j])
{
i++;
j++;
next[i]=j;
}
else
{
j=next[j];
}
}
}
void KMP()
{
int i=0;
int j=0;
get_next();
while(i<len&&j<len2)
{
if(j==-1||s[i]==s2[j])
{
i++;
j++;
}
else
{
j=next[j];
}
}
if(j==len2)
{
printf("yes\n");
return ;
}
else
{
printf("no\n");
return ;
}
}
int main(void)
{
while(scanf("%s%s",s1,s2)!=EOF)
{
len1=strlen(s1);
len2=strlen(s2);
if(len1<len2)
{
printf("no\n");
continue;
}
strcpy(s,s1);
strcat(s,s1);
len=2*len1;
memset(next,-1,sizeof(next));
KMP();
}
return 0;
}
代码3:KMP算法
<strong><span style="font-size:14px;">#include<stdio.h>
#include<string.h>
char str[200005];
char str1[100005];
char str2[100005];
int next[100005];
int len,len1,len2;
void get_next()
{
int i,j;
next[0]=0;
next[1]=0;
for(i=1;i<len2;i++)
{
j=next[i];
while(j&&str2[i]!=str2[j])
{
j=next[j];
}
if(str2[i]==str2[j])
{
next[i+1]=j+1;
}
else
{
next[i+1]=0;
}
}
}
int KMP()
{
int i,j=0;
for(i=0;i<len;i++)
{
while(j&&str[i]!=str2[j])
{
j=next[j];
}
if(str[i]==str2[j])
{
j++;
}
if(j==len2)
{
return 1;
}
}
return 0;
}
int main(void)
{
while(scanf("%s%s",str1,str2)!=EOF)
{
len1=strlen(str1);
len2=strlen(str2);
len=2*len1;
strcpy(str,str1);
strcat(str,str1);
get_next();
if(KMP())
{
printf("yes\n");
}
else
{
printf("no\n");
}
}
return 0;
}
</span></strong>