第一个能运行的用到后缀数组的程序^_^

/****************************
*应用:找出字符串中重复出现的最长字符窜
*方法:使用后缀数组
*****************************/
# include<stdio.h>
# include<stdlib.h>
# include<string.h>
# define NUM 1000
int cmp(const void *a,const void *b)
{
 return(strcmp(*(char**)a,*(char**)b));
}


int comlen(const char *p,const char *q)
{
 int i=0;
 if(p==NULL||q==NULL)
  return 0;
 while(*p&&(*p++==*q++))
  i++;
 return i;
}


int main()
{
  char *px[NUM], a[NUM],ch;
  int t=0,i,h,maxlen=0,maxi=0;
  /* 构造后缀数组px */
  while((ch=getchar())!='0')    
  {
   a[t]=ch;
   px[t]=&a[t];//巧妙的构造,省了空间和时间^_^
   t++;

  }
  a[t]='\0';
 
  qsort(px,t,sizeof(px[0]),cmp);       //对数组排序(这里复杂度有点高^_^|||)
  for(i=0;i<t-1;i++)
  {
   if((h=comlen(px[i],px[i+1]))>maxlen)  //找出最长字符窜
   {
    maxlen=h;
    maxi=i;
   }
  }
 
  char result[NUM];
  memcpy(result,px[maxi],maxlen);
  result[maxlen]='\0';
  printf("The result is: %s\n",result);
  system("pause");
  return 0;
}

posted on 2007-09-07 23:55  xmx  阅读(962)  评论(6)    收藏  举报

导航