【数据结构】后缀数组

前端之家收集整理的这篇文章主要介绍了【数据结构】后缀数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
// 字符串处理 后缀数组
void build_sa( char * s ) // 字符串从第一位开始读入,第0位任意填入一个字符便于操作
{
    int j,num,n = strlen( s )-1,m = 200,*x = a1,*y = a2;
    for( int i = 1; i <= m; i++ ) c[i] = 0;
    for( int i = 1; i <= n; i++ ) c[ x[i] = s[i] ]++;
    for( int i = 2; i <= m; i++ ) c[i] += c[i-1];
    for( int i = 1; i <= n; i++ ) sa[ c[ x[i] ]-- ] = i;
    for( int k = 1; k <= n; k <<= 1 )
    {
        num = 0;
        for( int i = n-k+1; i <= n; i++ ) y[++num] = i;
        for( int i = 1; i <= n; i++ ) if( sa[i] > k ) y[++num] = sa[i]-k;
        for( int i = 1; i <= m; i++ ) c[i] = 0;
        for( int i = 1; i <= n; i++ ) c[ x[i] ]++;
        for( int i = 2; i <= m; i++ ) c[i] += c[i-1];
        for( int i = n; i >= 1; i-- ) sa[ c[ x[ y[i] ] ]-- ] = y[i];
        swap( x,y );
        num = 1;
        x[ sa[1] ] = 1;
        for( int i = 2; i <= n; i++ )
            x[ sa[i] ] = y[ sa[i] ] == y[ sa[i-1] ] && y[ sa[i]+k ] == y[ sa[i-1]+k ]? num: ++num;
        if( num == n ) break;
        m = num;
    }
    num = 0;
    for( int i = 1; i <= n; i++ )
    {
        if( x[i] == 1 ) continue;
        if( num ) num--;
        j = sa[ x[i]-1 ];
        while( s[i+num] == s[j+num] ) num++;
        height[ x[i] ] = num;
    }
}
原文链接:https://www.f2er.com/datastructure/383214.html

猜你在找的数据结构相关文章