后缀数组求最长重复子串

790阅读 0评论2015-11-28 taohorse
分类:C/C++

转载自:http://blog.csdn.net/hackbuteer1/article/details/7968623

#include
using namespace std;

#define MAXCHAR 5000 //最长处理5000个字符

char c[MAXCHAR], *a[MAXCHAR];

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

int pstrcmp( const void *p1, const void *p2 )
{
    return strcmp( *(char* const *)p1, *(char* const*)p2 );
}


int main(void)
{
    char ch;
    int  n=0;
    int  i, temp;
    int  maxlen=0, maxi=0;
    printf("Please input your string:\n");

    n = 0;
    while( (ch=getchar())!='\n' )
    {
        a[n] = &c[n];
        c[n++] = ch;
    }
    c[n]='\0';     // 将数组c中的最后一个元素设为空字符,以终止所有字符串

    qsort( a, n, sizeof(char*), pstrcmp );
    for(i = 0 ; i < n-1 ; ++i )
    {
        temp=comlen( a[i], a[i+1] );
        if( temp>maxlen )
        {
            maxlen=temp;
            maxi=i;
        }
    }
    printf("%.*s\n",maxlen, a[maxi]);
    
    return 0;
}
上一篇:已知有个rand7()的函数,返回1到7随机自然数,用rand7()构造rand10() 随机1~10
下一篇:编程实现两个正整数的除法(不能用除法操作符)