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
ababcababababcababaaaaa
Sample Output
2 4 9 181 2 3 4 5
题意:求有哪些子串既是前缀又是后缀,输出他们的长度
思路:字符串本身肯定是一个答案。要去找下一个比他短的子串了,而next[n-1]表示的是以最后一个字符为结尾的串前后缀相同的最长的长度。
由于后缀的最后那些字符是确定了的,所以下一个答案显然是next[n-1]。
继续向前回溯。更短的子串显然是name[k...n-1],k大于n-1-next[n-1]
而name[0,next[n-1]-1] == name[n-1-next[n-1]...n-1] 那么我们相当于就是在name[0,next[n-1]-1] 继续找他的最长的前后缀,直到next为-1.也就是next数组的作用了
需要注意的一点是,要判断name[next[j]] == name[n - 1], 因为字符的第一个元素需要特判,他的next永远是0
而当name[0]恰好等于name[n -1]时,他是可以的。但是当他不相等的时候,是不行的。
代码:
#include#include #include #include #include