亲和串
亲和串
时间限制: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>