poj 2752 Seek the Name, Seek the Fame 【kmp】

本文探讨了如何通过next数组的性质,解决POJ平台上的问题,即找出字符串中既是前缀也是后缀的子串数量,并提供了解决问题的代码实现。

题目链接:http://poj.org/problem?id=2752

题意:求即是前缀有是后缀的子串有几个,输出长度。

思路:考察next数组的性质。具体见代码。

#include <stdio.h>  
#include <iostream>  
#include <math.h>  
#include <stdlib.h>  
#include <ctype.h>  
#include <algorithm>  
#include <vector>  
#include <string.h>  
#include <queue>  
#include <stack>  
#include <set>  
#include <map>  
#include <sstream>  
#include <time.h>   

using namespace std;

void get_next(char x[], int m, int Next[])
{
    int i, j;
    j = Next[0] = -1;
    i = 0;
    while (i < m)
    {
        while (-1 != j && x[i] != x[j]) j = Next[j];
        Next[++i] = ++j;
    }
}

int Next[1001000];
char a[1000100];
int ans[1000010];

int main()
{
    int t, num;
    while (scanf("%s", a) != EOF)
    {
        num = 0;
        int n = strlen(a);
        ans[num++] = n;
        get_next(a, n, Next);
        int t = Next[n - 1];
        while (t != -1)
        {
            if (a[t] == a[n - 1]) ans[num++] = t+1;
            t = Next[t];
        }
        for (int i = num - 1; i >= 0; i--)
        {
            printf("%d",ans[i]);
            if (i != 0) printf(" ");
            else printf("\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值