The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm:
Step1. Connect the father’s name and the mother’s name, to a new string S.
Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S).
Example: Father=’ala’, Mother=’la’, we have S = ‘ala’+’la’ = ‘alala’. Potential prefix-suffix strings of S are {‘a’, ‘ala’, ‘alala’}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix strings of S? (He might thank you by giving your baby a name:)
Input
The input contains a number of test cases. Each test case occupies a single line that contains the string S described above.
Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000.
Output
For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby’s name.
Sample Input
ababcababababcabab
aaaaa
Sample Output
2 4 9 18
1 2 3 4 5
求字符串中,既匹配字符串前缀,又匹配字符串后缀的字符串的长度。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 400000;
char pattern[maxn];
int nnext[maxn];
int sum[maxn];
void get_next()
{
int patternLen = strlen(pattern);
int j = -1, i = 0;
nnext[0] = -1;
while(i<patternLen)
{
if(j==-1||pattern[i]==pattern[j])
{
i++;
j++;
nnext[i] = j;
}
else
j = nnext[j];
}
}
int main()
{
while(~scanf("%s", pattern))
{
int k = 0;
int patternLen = strlen(pattern);
get_next();
for(int i=patternLen;i!=0;)
{
sum[k++] = nnext[i];//从后向前,寻找
i = nnext[i];
}
for(int i=k-2;i>=0;i--)//输出
printf("%d ", sum[i]);
printf("%d\n", patternLen);
}
return 0;
}
本文介绍了一种用于找出字符串中既是前缀也是后缀的子串长度的算法。该算法首先将父字符串与其自身连接起来形成新字符串S,并通过一种特殊的一次遍历方法计算出所有可能的匹配长度。
694

被折叠的 条评论
为什么被折叠?



