poj 2752 Seek the Name, Seek the Fame (字符串__KMP)

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


题目大意:问一个串中既是前缀又是后缀的不同子串的长度


解题思路:记题目所给串为str,长度为len,求出next数组,最长的那个子串长度即为next[len],再使i = next[len],此时的next[i]也是一个题目要求的子串,如此递归直到next[i] == -1 || next[i] == 0,这个str的长度len本身也算是一个答案。为什么这样呢?next数组就是记录与前缀匹配的长度,next[i] = 9,说明前str[9]以前的字符都已经匹配了,也可以这样理解,str[next[i]] == str[i],那我们递归到i = next[i],时,这个i就相当于最后一个字符了,i-1相当于倒一个...比如aaaaa,next数组是-1,0,1,2,3,next[4] = 3,则str[0],str[1],str[2],str[3] == str[1],str[2],str[3],str[4],所以以i = next[4]为结尾算出来的也是答案。


测试数据:

ababcababababcabab
aaaaa
fuckfuck

xxooxxooxxoo

abcde


代码:

#include <stdio.h>
#include <string.h>
#define MAX 400040


int next[MAX],ans[MAX];
char str[MAX];


int main()
{
	int i,j,k,len,tot;


	while (scanf("%s",str) != EOF) {

		len = strlen(str);
		i = 0,j = -1;
		next[i] = -1;
		while (i < len) {

			if (j == -1 || str[i] == str[j])
				i++,j++,next[i] = j;
			else j = next[j];
		}

		
		tot = 0,i = len;
		while (next[i] != 0 && next[i] != -1) {

			tot++;
			ans[tot] = next[i];
			i = next[i];
		}


		for (i = tot; i >= 1; --i)
			printf("%d ",ans[i]);
		printf("%d\n",len);
	}
}

本文章ZeroClock原创,但可以转载,因为我们是兄弟

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值