KMP算法

int func_equal(const char* p, int n, int k)
{
    int i = 0;   // 0 ~ k-1
    int j = n-k; // n-k ~ n-1

    while ( i <= k-1 )
    {
        if ( p[i] != p[j] )
        {
            return -1;
        }

        i++;
        j++;
    }

    return 0;
}

void func_get_next(const char* p, int* next)
{
    if ( strlen(p) == 0 ) return;

    next[0] = -1;
    if ( strlen(p) == 1 ) return;

    next[1] = 0;
    if ( strlen(p) == 2 ) return;

    int k = 0;
    for ( int n = 2; n < (int)strlen(p); ++n )
    {
        k = n-1;

        while ( k > 0 )
        {
            if ( 0 == func_equal(p, n, k) )
            {
                next[n] = k;
                break;
            }

            k--;
        }
        if ( k <= 0 )
        {
            next[n] = 0;
        }
    }
}

int func_string_match(const char* s, const char* p)
{
    unsigned int i = 0;
    unsigned int j = 0;

    int* next = new int[strlen(p)];
    func_get_next(p, next);

    while ( i < strlen(s) )
    {
        while ( s[i] == p[j] )
        {
            i++;
            j++;

            if ( j == strlen(p) )
            {
                delete[] next;
                return (i - strlen(p));
            }
        }

        j = next[j];
        if ( -1 == (int)j )
        {
            i++;
            j = 0;
        }
    }

    delete[] next;
    return -1;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章