题意:给定一个字符串, 如 alala, 求既是它前缀,又是它后缀的子串( a, ala, alala ) ,按升序输出所以可能的子串的长度。
题解:next 函数的应用。当然用hash也可以。
#include <iostream>
using namespace std;
#define N 400005
char str[N];
int next[N];
void get_next ( int n )
{
int i = 0, j = -1;
next[0] = -1;
while ( i < n )
{
if ( j == -1 || str[i] == str[j] )
{
++i; ++j; next[i] = j;
}
else j = next[j];
}
}
void print ( int n )
{
if ( next[n] != 0 )
print(next[n]);
printf("%d ",n);
}
int main()
{
while ( scanf("%s",str) != EOF )
{
if ( str[0] == '.' )
break;
int len = strlen(str);
get_next( len );
print ( len );
putchar('\n');
}
return 0;
}