题目链接: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原创,但可以转载,因为我们是兄弟