int comlen(const char* str1,const char* str2){ assert((str1!=0)&&(str2!=0)); int len=0; while(*str1!='\0'&&*str2!='\0'&&*str1++==*str2++){ len++; } return len; } bool less(char* str1,char* str2){ return strcmp(str1,str2)<=0; } /*后缀数组法*/ void longestRepeatedSubstring2(char* string){ int n=strlen(string); char** a=new char*[n]; for(int i=0;i<n;i++){ a[i]=string+i; } sort(a,a+n,::less); int maxlen=-1,maxi; for(int i=0;i<n-1;i++){ int len=comlen(a[i],a[i+1]); if(len>maxlen){ maxlen=len; maxi=i; } } printf("%.*s\n",maxlen,a[maxi]);//使用"*"精度输出字符串中的maxlen个字符 delete []a; } /*穷举法*/ void longestRepeatedSubstring1(char* str){ int n=strlen(str); int maxlen=-1,maxi,maxj; for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ int len=comlen(str+i,str+j); if(len>maxlen){ maxlen=len; maxi=i; maxj=j; } } } cout<<"longest repeated substring is: "; printf("%.*s\n",maxlen,str+maxi); printf("appear at %d and %d\n",maxi,maxj); }