题解
之前已经做过详细的笔记了,有点类似于DP的思路
C++ 代码
#include <iostream>
using namespace std;
const int N = 100010;
const int M = 1000010;
int ne[N];
char p[N],s[M];
int main(){
int n , m;
cin >> n >> p + 1 >> m >> s + 1; //char数组从下标1开始
//求next数组
for(int i = 2 , j = 0;i <= n;++i){
while(j && p[j + 1] != p[i]) j = ne[j];
if(p[j + 1] == p[i]) ++j;
ne[i] = j;
}
//开始匹配
for(int i = 1,j = 0;i <= m;++i){
while(j && p[j + 1] != s[i]) j = ne[j];
if(p[j + 1] == s[i]) j ++;
if(j == n){
cout << i - n << " ";
j = ne[j];
}
}
return 0;
}