#include<iostream>
#include<cstring> //用trlen
using namespace std;const int N = 1e6 + 10;
char s[N], p[N]; //s为匹配串,p为模板串
int ne[N]; //记录p的next数组
int main() {scanf("%s%s", s + 1,p + 1); //从1开始读入int len_p = strlen(p + 1),len_s = strlen(s + 1);for (int i = 2, j = 0; i <= len_p; i ++ ) //j是前缀倒是第二个字母位置,i是后缀最后一个位置{while (j && p[i] != p[j + 1]) j = ne[j]; //不想等就回溯if (p[i] == p[j + 1]) j ++ ; //相等就继续ne[i] = j; //记录}for (int i = 1, j = 0; i <= len_s; i ++ ) //i指向匹配串,j指向模板串{while (j && s[i] != p[j + 1]) j = ne[j]; if (s[i] == p[j + 1]) j ++ ;if (j == len_p) //匹配成功{printf("%d\n",i - len_p + 1);j = ne[j]; //回溯到??// 匹配成功后的逻辑}}for(auto i = 1;i <= len_p;++i) cout << ne[i] << ' ';}
感觉懂了!