搞懂算法思路后,代码相较于朴素的kmp更易理解
#include <bits/stdc++.h>
using namespace std;
string s , p ;
int n , m ;
int main()
{
cin >> n >> p >> m >> s ;
string str = p + '#' + s ;
vector<int > pi(str.size()) ;
for (int i = 1 ; i < str.size() ; i ++)
{
int len = pi[i - 1];
while (len && str[i] != str[len]) len = pi[len - 1] ;
if (str[i] == str[len])
{
pi[i] = len + 1 ;
if (pi[i] == n) cout << i - n * 2 << ' ' ;
}
}
return 0 ;
}