典型的KMP算法,,,,,话说KMP算法还有个俗名,“看毛片”算法,,,学习了。。。。具体KMP算法太复杂,想学得话看严蔚敏的数据结构,,讲得很详细,,仔细看应该是比较容易理解的。题目:
AABCD CDAA ASD ASDF
yes no
#include <iostream> #include <string> #include <string.h> #include <cstdio> using namespace std; const int N=100010; int nextt[N],len1,len2,len; char s[N],ss[N],str[2*N]; void getnext(){ nextt[1]=0; int i=1,j=0; while(i<=len2){ if(j==0||ss[i]==ss[j]){ ++i;++j; if(ss[i]!=ss[j]) nextt[i]=j; else nextt[i]=nextt[j]; } else j=nextt[j]; } } int kmp(){ int i=1,j=1; while(i<=len&&j<=len2){ if(j==0||str[i]==ss[j]){ ++i;++j; } else j=nextt[j]; } if(j>len2) return i-len2; return 0; } int main(){ while(scanf("%s%s",s+1,ss+1)!=EOF){ memset(nextt,0,sizeof(nextt)); len1=strlen(s+1); len2=strlen(ss+1); if(len1<len2) {printf("no\n");continue;} for(int i=1;i<=len1;++i) str[i]=s[i]; len=len1; for(int i=1;i<=len1;++i) str[++len]=s[i]; getnext(); int flag=kmp(); if(flag==0) printf("no\n"); else printf("yes\n"); } return 0; }