KMP算法模板

http://www.matrix67.com/blog/archives/115

求next函数模板:

void GetNext(char *s)

{

    int len = strlen(s);

    int i,j;

    i = 0; j = -1;//j从0开始,i从1开始

    next[0] = -1;

    for (i = 1; i < len; ++i)

    {

        while (j > -1 && s[j + 1] != s[i])//不相同的话j就跳跃知道相同或者成为-1

        j = next[j];

        if (s[j + 1] == s[i]) ++j;//相同更新j

        next[i] = j;//每一次都要求出next[i]

    }

}

  

kmp模板:

void kmp(char *s1,char *s2)//s1副串 s2主串

{

    int len1 = strlen(s1);

    int len2 = strlen(s2);

    int i,j = -1;

    int ans = 0;

    for (i = 0; i < len2; ++i)

    {

        while (j > -1 && s1[j + 1] != s2[i]) j = next[j];

        if (s1[j + 1] == s2[i]) ++j;

        if (j == len1 - 1)//找到子串,后继续查找

        {

            ans++;

            j = next[j];

        }

    }

    printf("%d\n",ans);

}

  

你可能感兴趣的:(KMP)