奥赛一本通 1458 Seek the Name, Seek the Fame

1458 Seek the Name, Seek the Fame

题目大意

求字符串的所有既是前缀又是后缀的子串。

知识要点

KMP

解题思路

border 的 border 也是原串的 border,直接使用 KMP 算法求解。

参考代码

#include <bits/stdc++.h>
using namespace std;

const int N = 400005;
char s[N];
int f[N], ans[N];
int main() {
    while(scanf("%s", s) == 1) {
        int n = strlen(s), num = 0;
        for(int i = 1, j = 0; i < n; i++) {
            while(j && s[i] != s[j]) j = f[j - 1];
            if(s[i] == s[j]) j++;
            f[i] = j;
        }

        for(int i = n; i; i = f[i - 1]) ans[++num] = i;
        while(num) printf("%d ", ans[num--]);
        puts("");
    }
    return 0;
}
posted @ 2026-09-21 15:38  萧西待水  阅读(16)  评论(0)    收藏  举报