题目链接
点此跳转
代码
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#define LL long long
#define mem(a, b) memset(a, b, sizeof a)
#define lowbit(x) (-x&x)
#define IOS ios::sync_with_stdio(false),cin.tie(0)
#define endl '\n'
#define rev(x) reverse(x.begin(), x.end())
#define INF 0x3f3f3f3f
using namespace std;
const int N = 1000010;
int ne[N];
string s1, s2;
void get_ne(string t) {
int j = 0, k = -1;
ne[0] = -1;
while (j < t.size()) {
while(k != -1 && t[j] != t[k]) k = ne[k];
ne[++ j] = ++ k;
}
}
void kmp(string s, string t, int pos) {
get_ne(s2);
int i = pos, j = 0, tlen = t.size(), slen = s.size();
while (i < slen) {
if (j == -1 || s[i] == t[j]) i ++ , j ++ ;
else j = ne[j];
if (j == tlen) {
cout << i - j + 1 << endl;
j = ne[j];
}
}
}
void solve() {
cin >> s1 >> s2;
kmp(s1, s2, 0);
for (int i = 1; i <= s2.size(); i ++ ) cout << ne[i] << ' ';
}
int main() {
IOS;
solve();
return 0;
}