顺序串的简单模式匹配(定位)

设S=‘ababcabcacbab’, P=‘abcac’,从S的第1个字符开始,依次比较S和P中的字符,如果没有完全匹配,则从S第2个字符开始,再次比较…如此重复,直到找到P的完全匹配或者不存在匹配。用数学语言描述,就是比较SiSi+1…Si+n-1和P0P1…Pn-1,如果出现不匹配,则令i=i+1,继续这一过程,直到全部匹配,或者i>(m-n)。匹配过程如下(红色字体表示本趟比较中不匹配的字符)

1.第1趟
S: a b a b c a b c a c b a b
P: a b c

第2趟
S: a b a b c a b c a c b a b
P: a

第3趟
S: a b a b c a b c a c b a b
P: a b c a c

第4趟
S: a b a b c a b c a c b a b
P: a

第5趟

S: a b a b c a b c a c b a b
P: a

第6趟

S: a b a b c a b c a c b a b
P: a b c a c


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// BF (Brute Force) algorithm
// worst time complexity : O(m*n)
static int bf (const char*, const char*);
static int bf2(const char*, const char*);

int main(void)
{
    char* str = "ababcabcacbab";
    char* ptn = "abcac";

    printf("match1 at %d\n", bf(str, ptn));
    printf("match2 at %d\n", bf2(str, ptn));

    return 0;
}

int bf(const char* _str, const char* _ptn)
{
    int m, n, i, j;

    m = strlen(_str);
    n = strlen(_ptn);

    i = 0; j = 0;
    while(i<m && j<n)
    {
        if(_str[i] == _ptn[j])
        {
            printf("OK %d %d %c %c\n", i, j, _str[i], _ptn[j]);
            ++i;  ++j; 
        }
        else
        {
            printf("NO %d %d %c %c\n", i, j, _str[i], _ptn[j]);
            i = i-j+1; j = 0; 
        }
    }

    if(j >= n)
        return i-n;
    else
        return -1;
}



int bf2(const char* _str, const char* _ptn)
{
    int m, n, i, j;

    m = strlen(_str);
    n = strlen(_ptn);

    i = 0; j = 0;
    for(i=0; i<=(m-n); ++i)
    {
        for(j=0; j<n; ++j)
        {
            if(_str[i+j] != _ptn[j])
            {
                printf("NO %d %d %c %c\n", i+j, j, _str[i+j], _ptn[j]);
                break;
            }
            else
                printf("OK %d %d %c %c\n", i+j, j, _str[i+j], _ptn[j]);
        }
        if(n == j)  return i;
    }

    return -1;
}

猜你喜欢

转载自blog.csdn.net/weixin_43904021/article/details/87726110