POJ 2752 Seek the Name, Seek the Fame(kmp)

本文详细介绍KMP算法的应用场景之一:寻找字符串中相同前缀和后缀的长度。通过KMP next数组来高效地解决这一问题,并给出了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

给你一个串,如果这个串存在一个长度为n的前缀串,和长度为n的后缀串,并且这两个串相等,则输出他们的长度n。求出所有的长度n。

解析:

此题考察kmp next[]数组的应用,不难。

AC代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cstdlib>
using namespace std;
typedef long long ll;
const int N = 400005;
char str[N];
int jump[N];

vector<int> ans;
void getNext() {
    int j = 0, k = -1;
    int len = strlen(str);
    jump[0] = -1;
    while(j < len) {
        if(k == -1 || str[j] == str[k])
            jump[++j] = ++k;
        else k = jump[k];
    }
}

int main() {
    while(scanf("%s", str) != EOF) {
        ans.clear();
        getNext();
        int cur = strlen(str);
        while(cur > 0) {
            ans.push_back(cur);
            cur = jump[cur];
        }
        sort(ans.begin(), ans.end());
        printf("%d", ans[0]);
        for(int i = 1; i < ans.size(); i++) {
            printf(" %d", ans[i]);
        }puts("");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值