0
点赞
收藏
分享

微信扫一扫

FZU - 1901 Period II(KMP next数组的理解)

zmhc 2023-04-07 阅读 68


题目大意:给你一个字符串,问这个字符串前缀等于后缀的所有后缀的开始位置

解题思路:就是next数组的理解了,出现的位置就是len - next[i]了

#include <cstdio>
#include <cstring>
const int N = 1000010;

char str[N];
int next[N], ans[N];
int len, cas = 1, cnt = 0;

void getNext() {
    len = strlen(str);
    int i = 0, j = -1;
    next[0] = -1;
    while (i < len) {
        if (j == -1 || str[i] == str[j]) {
            i++; j++;
            next[i] = j;
        }
        else j = next[j];
    }
}

void getAns() {
    int pos = next[pos];
    while (!(pos == 0 || pos == -1)) {
        ans[++cnt] = len - pos;
        pos = next[pos];
    }
}

void solve() {
    getNext();
    cnt = 0;
    getAns();
    printf("Case #%d: %d\n", cas++, cnt + 1);
    for (int i = 1; i <= cnt; i++)
        printf("%d ", ans[i]);
    printf("%d\n", len);

}

int main() {
    int test;
    scanf("%d", &test);
    while (test--) {
        scanf("%s", str);
        solve();
    }
    return 0;
}


举报

相关推荐

0 条评论