串的匹配模式(KMP算法)

 

//串的模式匹配
//1.朴素的模式匹配算法
int Index1(char S[], char P[], int pos)
{//查找并返回串P在主串S中从pos位置开始的位置,否则返回-1
    int i, j, slen, plen;
    i = pos; j = 0;
    slen = strlen(S); plen = strlen(P);
    while (i < slen && j < plen)
    {
        if (S[i] == P[j]){
            ++i; ++j;
        }
        else{
            i = i - j + 1;//主串位置回退
            j = 0;
        }
    }
    if (j == plen)
        return i - plen;
    return -1;
}
//2.改进的模式匹配算法(KMP算法)
void GetNext(char p[], int next[])
{
    int i, j, len;
    i = 0; j = -1;
    len = strlen(p);
    next[0] = -1;
    while (i < len)
    {
        if (-1 == j || p[i] == p[j])
        {
            ++i; ++j;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }
}
int Index_KMP(char S[], char P[], int pos, int next[])
{
    int i, j, slen, plen;
    i = pos; j = 0;
    slen = strlen(S); plen = strlen(P);
    while (i < slen && j < plen)
    {
        if (-1 == j || S[i] == P[j])
        {
            ++i; ++j;
        }
        else
        {
            j = next[j];
        }
    }
    if (j == plen)
        return i - plen;
    return -1;
}


void main()
{
    char* s = "ababcdsfds";
    char* p = "abab";
    int d = Index1(s, p, 0);
    const int len = strlen(s);
    int next[5];
    GetNext(p, next);
    int d2 = Index_KMP(s, p, 0, next);
    printf("%d\n%d", d,d2);
    
}

 

**

posted @ 2022-12-12 17:44  htj10  阅读(59)  评论(0编辑  收藏  举报
TOP