poj2752—Seek the Name, Seek the Fame

本文介绍了一种用于寻找字符串中既是前缀又是后缀的子串的长度的方法,并提供了一个具体的编程实现示例。通过KMP算法的变体,文章展示了如何高效地找到所有符合条件的子串长度。

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

传送门:点我

Input
The input contains a number of test cases. Each test case occupies a single line that contains the string S described above.

Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000.
Output
For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby's name.
Sample Input
ababcababababcabab
aaaaa
Sample Output
2 4 9 18
1 2 3 4 5

题意:给定一个字符串s,从小到大输出s中既是前缀又是后缀的子串的长度。

贴代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
using namespace std;
#define N 400006
char s[N];
int Next[N];
void make_Next(int n)
{
    int i,j;
    for(i=1,j=0; i<n; i++)
    {
        while(j>0&&s[i]!=s[j])
            j=Next[j-1];
        if(s[i]==s[j])
            j++;
        Next[i]=j;
    }
}
int main()
{
    int t,j;
    cin>>t;
    while(~scanf("%s",s))
    {
        int len=strlen(s);
        Next[0]=0;
        make_Next(len);
        stack<int> sta;
        j=len-1;
        while(Next[j]!=0)
        {
            sta.push(Next[j]);
            j=Next[j-1];
        }
        while(!sta.empty())
        {
            printf("%d ",sta.top());
            sta.pop();
        }
        printf("%d\n",len);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值