POJ 2752 Seek the Name, Seek the Fame (next数组)

题目链接

题意:给定若干只含小写字母的字符串(这些字符串总长≤400000),在每个字符串中求出所有既是前缀又是后缀的子串长度。

例如:ababcababababcabab,既是前缀又是后缀的子串:ab,abab,ababcabab,ababcababababcabab。

分析:根据next数组的定义求解。注意串本身是一个,可以单独输出。

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
const double eps=1e-6;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int mod=1e9+7;
const int maxn=4e5+10;

int nx[maxn];
void getnx(string x){
	int m=x.size();
	int i,j;
	j=nx[0]=-1;
	i=0;
	while (i<m){
		while (-1!=j && x[i]!=x[j]) j=nx[j];
		//if (x[++i]==x[++j]) nx[i]=nx[j];
		nx[++i]=++j;
	}
}
/*int kmp(string s, string t) { 
	int n=s.size();
	int m=t.size();
	int i=0,j=0;
	getnx(t);
	while (i<n && j<m) {
		while (-1!=j && s[i]!=t[j]) j=nx[j];
		i++;
		j++;
	}
	if (j==m)
		return i-j;
	else return -1;
}*/

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	string s;
	while (cin>>s){		
		memset(nx,0,sizeof(nx)); 
		getnx(s);
		vector <int> ans;
		int len=s.size();
		while (nx[len]){
			ans.push_back(nx[len]);
			len=nx[len];
		}
		for (int i=ans.size()-1; i>=0; i--)
			cout<<ans[i]<<" ";
		cout<<s.size();
		cout<<endl;
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值