POJ-2752-Seek the Name, Seek the Fame

本文深入探讨了一种字符串匹配算法,通过实例讲解了如何求解一个字符串的最长公共前缀和后缀,以及如何通过next数组的巧妙应用,输出每个位置的最长公共前后缀长度。文章提供了详细的代码实现,帮助读者理解并掌握这一算法。

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

Seek the Name, Seek the Fame

The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm:

Step1. Connect the father’s name and the mother’s name, to a new string S.
Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S).
Example:
Father=‘ala’, Mother=‘la’, we have S = ‘ala’+‘la’ = ‘alala’. Potential prefix-suffix strings of S are {‘a’, ‘ala’, ‘alala’}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix strings of S? (He might thank you by giving your baby a name:)
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
题目传送门:POJ-2752

解题思路

这个题的大概意思就是要求一个字符串的最长公共前缀和后缀,求是的确很好求但是如何输出呢?每个位置的最长公共前后缀这就是个问题,其实也不是很难,我们只需把next数组的值到这输出一下就行,就想并查集一样,一直循环就行了,因为我们在求next数组的时候已经把位置给记录好了

代码

#include<string.h>
#include<vector>
#include<stdio.h>

using namespace std;
#define vce vector<int>
char a[400400];
int v[400400];
int nu[400400];
int main()
{
	while(~scanf("%s",a))
	{
		int len=strlen(a);
		memset(v,0,sizeof v);
		v[0]=0;
		int j;
		//求next数组 
		for(int i=1;i<len;i++)
		{
			j=v[i-1];
			while(j>0&&a[i]!=a[j])
			{
				j=v[j-1];
			}
			if(a[i]==a[j]) j++;
			v[i]=j;
		}
		int i=v[len-1];
		nu[0]=len;//需要将数组倒着存一下 
		int k=1;
		while(i!=0)//一旦i=0就说明找到头了,不用找了 
		{
			if(i>0) nu[k++]=i;
		    i=v[i-1];
		}
		for(int i=k-1;i>=0;i--) 
		{
			if(i==k-1) printf("%d",nu[i]);
			else printf(" %d",nu[i]);
		}
		printf("\n");
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值