POJ2752(KMP的next数组的理解应用)

Seek the Name, Seek the Fame - POJ 2752 - Virtual Judge

知道KMP算法的都知道其中有个很神奇的next数组,其中next数组就是来记录当前字符以前的字符串中  最长的  前缀等于后缀的  串  的长度,正好符合题意,这个题这个串的本身其实也是前缀等于后缀,不能忘了,这里next的优化不能用,还是得理解优化的使用范围,是为了匹配更快,避免重复的递归调用,而这里需要的是前缀和后缀相等的字符串的长度,正好与优化前的next数组对应上了

AC代码:

#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <set>
#include <cmath>
#include <algorithm>
using namespace std;



int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);

    string s;
    while (cin >> s) {
        int len = s.size();
        vector<int> next(len + 1);
        next[0] = -1;
        int j = 0, k = -1;
        while (j < len) {
            if (k == -1 || s[j] == s[k]) {
                j++;
                k++;
                next[j] = k;
            }
            else {
                k = next[k];
            }
        }
        vector<int> ans(len + 1);
        int cnt = 0;
        int t = next[len - 1];
        while (t != -1) {
            if (s[t] == s[len - 1]) ans[cnt++] = t + 1;
            t = next[t];
        }
        for (int i = cnt - 1; i >= 0; i--) {
            cout << ans[i] << " ";
        }
        cout << len << "\n";
    }

    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值