POJ 2752 Seek the Name, Seek the Fame(求所有既是前缀又是后缀的子串长度)

本文提供了一种算法解决给定字符串中所有前缀后缀(既是前缀又是后缀的子串)长度的问题。通过计算next数组,我们可以找到最大前缀后缀长度,并进一步获取所有符合条件的子串长度。

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

题意:给你一个字符串,求出所有前缀后缀(既是前缀又是后缀的子串)的长度

思路:首先整个字符串肯定既是前缀又是后缀,为最大的前缀后缀。

假设next[len] = k,也即:s[1,k] = s[len-k+1,len]此时s[1,k]是前缀后缀。

处理完next[len]后跳转到next[k+1],用这种方法可以得到所有的前缀后缀。

code:

 1 #include <cstdio>
 2 #include <cstring>
 3 const int MAXN = 400005;
 4 char str[MAXN];
 5 int next[MAXN];
 6 int ans[MAXN];
 7 void GetNext(int len)
 8 {
 9     int i = 0;
10     int j = -1;
11     next[0] = -1;
12     while (i < len)
13     {
14         if (-1 == j || str[i] == str[j]) next[++i] = ++j;
15         else j = next[j];
16     }
17 }
18 
19 int main()
20 {
21     while (scanf("%s", str) == 1)
22     {
23         int len = strlen(str);
24         GetNext(len);
25         int t = -1;
26         ans[++t] = len;
27         while (next[len] > 0)
28         {
29             ans[++t] = next[len];
30             len = next[len];
31         }
32         for (int i = t; i > 0; --i) printf("%d ", ans[i]);
33         printf("%d\n", ans[0]);
34     }
35     return 0;
36 }

 

转载于:https://www.cnblogs.com/ykzou/p/4468945.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值