模式匹配KMP POJ2752

本文介绍如何使用KMP算法解决一个字符串问题:寻找所有满足前缀等于后缀的子串长度。通过实现两种不同的next数组生成方法,最终输出所有符合条件的子串长度。

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

题目地址:http://poj.org/problem?id=2752


题目大意:求一个字符串中满足:前缀等于后缀的可能的子串的长度,串的长度小于等于400000。


解题思路:kMP,貌似发现了清华的数据结构书中的一点错误,明个再研究研究。。。


程序代码:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#define N 400010

int next[N];
int res[N];
char str[N];
void GetNext()
{
    next[0] = -1;
    int i = 0;
    int j = -1;
    while (i < strlen(str))
    {
        if (j == -1 || (str[i] == str[j]))
        {
            i++;
            j++;
           // if (str[i] == str[j]) next[i] = next[j];
           // else
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
}

void getNext()
{
        int i=1;
        int j=-1;
        next[0]=-1;
        while (i < strlen(str))
        {
                while (j != -1 && str[j+1] != str[i])
                    j = next[j];
                if (str[j+1] == str[i])j++;
                next[i] = j;
                i++;
        }
}
int main()
{
    while (~scanf("%s", str))
    {
        //GetNext();
        getNext();
        int j = strlen(str) - 1;
        int cnt = 0;
        while (j != -1)
        {
            res[cnt] = j + 1;
            cnt++;
            j = next[j];
        }
        for (int i = cnt - 1; i >= 0; i--)
        {
            printf("%d ", res[i]);
        }
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值