KMP

#include <bits/stdc++.h>

using namespace std;

const int N = 1e6 + 5;

int n, p[N];

string s;

int main() {
  ios::sync_with_stdio(0);
	cin.tie(0);
  cin >> s;
  n = s.size();
  s = " " + s;
  p[0] = -1;
  for(int i = 2, j = 0; i <= n; ++i) {
    for(; j >= 0 && s[i] != s[j + 1]; j = p[j]) {
    }
    j++;
    p[i] = j;
  }
  for (int i = 1; i <= n; i++) {
  	cout << p[i] << " ";
	}
  return 0;
}
posted @ 2025-07-25 19:28  libohan0518  阅读(8)  评论(0)    收藏  举报