求最长重复字串
一个长度为10000的字符串,写一个算法,找出最长的重复子串,如abczzacbca,结果是bc。
2010-03-09 21:57
2010-03-10 11:28
2010-03-10 11:36
2010-03-10 11:58
2010-03-10 13:45
2010-03-10 18:13
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MIN(a,b) (a>b?b:a)
#define MAXCHAR 10000
int main (int argc,char **argv)
{
char *c = (char *)malloc(MAXCHAR*sizeof(char));
char *bestchar;
int bestmatch[2]={0,0};
int beststep,step,maxstep;
int i,j;
int len;
printf("Pleas input the string:\n");
gets(c);
len = strlen(c);
//get best match
for (i=0;i<len ;i++ )
for (j=i+1;j<len ;j++ )
{
if (c[i] == c[j])
{
step = 1;
maxstep = MIN(len-i,len-j);
while(step<maxstep && c[i+step]==c[j+step]) step++;
if (bestmatch[1]<step)
{
bestmatch[0] = i;
bestmatch[1] = step;
}
}
}
//copy best match to bestchar
bestchar = (char *)malloc(bestmatch[1]*sizeof(char));
for (i=0;i<bestmatch[1] ;i++ ) bestchar[i] = c[i+bestmatch[0]];
bestchar[i]='\0';
printf("The longest copied string is %s\n",bestchar);
free(bestchar);
free(c);
}

2010-03-11 13:39