这里放一个模板,话说c++抽掉后我调了好久
1 #include<cstdio> 2 #include<string> 3 #include<iostream> 4 using namespace std; 5 int p[101]; 6 int main(){ 7 string a,b; 8 cin>>a>>b; 9 int n=a.length(),m=b.length(); 10 a=" "+a;b=" "+b; 11 int j=0; 12 for(int i=2;i<=m;i++){ 13 while(j>0&&b[j+1]!=b[i])j=p[j]; 14 if(b[j+1]==b[i])j++; 15 p[i]=j; 16 } 17 j=0; 18 for(int i=1;i<=n;i++){ 19 while((j>0)&&(b[j+1]!=a[i])) 20 j=p[j]; 21 if (b[j+1]==a[i])j++; 22 if (j==m) {printf("%d",i-m+1);break;} 23 } 24 return 0; 25 }