#include<string> #include<stdio.h> #include<iostream> #include<vector> using namespace std; string s1,s2; vector<int>f; void init() { f[0] = 0; f[1] = 0; int n = s2.size();//n = f.size()后面f[i+1]会越界 for(int i=1,j=0;i<n;i++){ j = f[i]; while(j && s2[i] != s2[j]) j =f[j]; f[i+1] = s2[j] == s2[i] ?j+1:0; } } void find() { int n =s1.size(); int m = s2.size(); for(int i=0,j=0;i<n;i++){ while(j && s1[i] != s2[j]) j = f[j]; if(s1[i] == s2[j]) j++; if(m == j) printf("%d\n",i-m+2); } } int main() { cin>>s1>>s2; f.resize(s2.size()+1); init(); find(); for(int i=1;i<s2.size()+1;i++) printf("%d ",f[i]); return 0; }
原文:https://www.cnblogs.com/zxzmnh/p/12109959.html