http://acm.hdu.edu.cn/showproblem.php?pid=2203
KMP算法,只要把模式串扩大二倍就可以解决首尾的匹配问题了
比如AABCD扩大一倍为AABCDAABCD在用CDAA匹配就可以求出结果
# include <iostream> # include <cstring> # include <string> using namespace std; const int N=1e6+5; int Next[N]; void GetNext(string s) { int len=s.length(); int j,k; j=0; Next[0]=k=-1; while(j<len) { if(k==-1 || s[j]==s[k]) { ++j; ++k; Next[j]=k; } else { k=Next[k]; } } } int KMP(string s1,string s2) { int len1=s1.length(); int len2=s2.length(); int j,i; j=i=0; GetNext(s2); while(i<len1 && j<len2) { if(j==-1 || s1[i]==s2[j]) { ++j; ++i; } else { j=Next[j]; } } if(j==len2) return i-j+1; else return -1; } int main() { string s1,s2; std::ios::sync_with_stdio(false); while(cin>>s1>>s2) { bool flag=false; s1+=s1;//只需要扩大s1的长度就可以了,其他就是普通的KMP算法 if(KMP(s1,s2)>0) cout<<"yes"; else cout<<"no"; cout<<endl; } return 0; }