KMP算法

来源:互联网 发布:js微信通讯录字母索引 编辑:程序博客网 时间:2024/06/07 19:19
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;}

0 0
原创粉丝点击