另外一个KMP的练习
依旧建立next数组
View Code
#include "stdio.h"
#include "string.h"
int next[1000000];
char str[1000000];
void ini_next(int len)
{
int i = 0 , j = -1;
next[0] = -1;
while( i <= len )
{
if( j == -1 || str[i] == str[j] )
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int main()
{
int t = 1, len , i , j;
while(scanf("%d",&len) && len)
{
memset(next,0,sizeof(next));
scanf("%d",&len);
scanf("%s",str);
ini_next(len);
printf("Test case #%d\n",t++);
for( i = 2 ; i <= len ; i++ )
{
if(i%(i-next[i]) == 0 && next[i] != 0)
{
printf("%d %d\n",i,i/(i-next[i]));
}
}
printf("\n");
}
return 0;
}