fail 失配数组 fail[i]表示以i为结尾的非前缀子串与s的前缀的最大匹配长度
在拼接两字符串后,求fail数组的同时就能求出匹配位置(fail[i]==len_origin的i-2*len_origin)
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int MAXN=2200002; char s[MAXN],tmp[MAXN]; int fail[MAXN]; int olen,lens; int main(){ scanf("%s%s",tmp+1,s+1); olen=strlen(s+1); strcat(s+1,"."); strcat(s+1,tmp+1); lens=strlen(s+1); for(int i=2,j=0;i<=lens;i++){ while(j>0&&s[i]!=s[j+1]) j=fail[j]; if(s[i]==s[j+1]) j++; fail[i]=j; if(j==olen) cout<<i-olen-olen<<endl; } for(int i=1;i<=olen;i++) cout<<fail[i]<<" "; return 0; }