KMP模板題

直接套模板即可!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 2000000
#define M 200000

void cal_next( char * str, int * next, int len )
{
    int i, j;

    next[0] = -1;
    for( i = 1; i < len; i++ )
    {
        j = next[ i - 1 ];
        while( str[ j + 1 ] != str[ i ] && ( j >= 0 ) )
        {
            j = next[ j ];
        }
        if( str[ i ] == str[ j + 1 ] )
        {
            next[ i ] = j + 1;
        }
        else
        {
            next[ i ] = -1;
        }
    }
}

unsigned int KMP( char * str, int slen, char * ptr, int plen, int * next )
{
    int s_i = 0, p_i = 0;
    unsigned int all = 0;

    while( s_i <= slen )
    {
        if( p_i == plen )
        {
            all++;
            p_i = next[p_i - 1] + 1;
        }
        if( str[ s_i ] == ptr[ p_i ] )
        {
            s_i++;
            p_i++;
        }
        else
        {
            if( p_i == 0 )
            {
                s_i++;
            }
            else
            {
                p_i = next[ p_i - 1 ] + 1;
            }
        }
    }
    return all;
}

int main()
{
    int n;
    char str[ N ] = {0};
    char ptr[ M ] = {0};
    int slen, plen;
    int next[ N ];

    scanf( "%d", &n );
    getchar();
    while( n-- )
    {
        scanf( "%s%s", ptr, str );
        slen = strlen( str );
        plen = strlen( ptr );
        cal_next( ptr, next, plen );
        printf( "%u\n", KMP( str, slen, ptr, plen, next ) );
    }
    return 0;
}

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