HDU 2203 亲和串

题解:将原来的串扩展为两倍,然后用KMP匹配。

#include <cstdio> 
#include <cstring>
char str[200005],pat[100005];
int next[100005],N,M;
void getnext(){
    int i=1,j=0;next[1]=0;
	  while(i<M){
		    if(j==0||pat[i]==pat[j])next[++i]=++j;
		    else j=next[j];
	  }
}
int KMP(){
	  int i=0,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
");continue;}
		    for(int i=1;i<=N;i++)str[i+N]=str[i];
		    str[2*N+1]='';getnext();
	     	printf(KMP()?"yes
":"no
");
	  }return 0;
}
原文地址:https://www.cnblogs.com/forever97/p/3927963.html