POJ 2752 Seek the Name, Seek the Fame(KMP)

理解好nxt数组后这个题目不难

题目让求所有原串前后缀,前后缀就是既是前缀也是后缀的字符串。

nxt[len]指第len+1个字符匹配不上后要跳转的字符,那么以nxt[len]-1为结尾的前缀一定是该字符串的后缀,

然后以nxt[nxt[len]]-1为结尾的前缀也一定是该字符串的后缀,依次我们就可以找到所有前后缀了,,最后不要加上原串本身。

#pragma warning(disable:4996)
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

char s[400005];
int nxt[400005];

void get_nxt(){
	int len = strlen(s);
	nxt[0] = -1;
	int i = 0, j = -1;

	while (i < len){
		if (j == -1 || s[i] == s[j]){
			i++, j++;
			nxt[i] = j;
		}
		else j = nxt[j];
	}
}

int main(){
	//freopen("in.txt", "r", stdin);
	while (scanf("%s", s) != EOF){
		get_nxt();
		vector<int>ans;

		int j = nxt[strlen(s)];
		while (j != -1){
			if (j != 0)ans.push_back(j);
			j = nxt[j];
		}

		ans.push_back((int)strlen(s));
		sort(ans.begin(), ans.end());

		for (int i = 0; i < ans.size(); i++)printf("%d", ans[i]), printf(i == (int)ans.size() - 1 ? "\n" : " ");

	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值