【模板】KMP字符串匹配

计算Next数组

int m,n;
char s[maxn], t[maxm];
int Next[maxm];

void getnext() 
{
    Next[0] = -1;
    int i = 0, j = -1;
    while(i<m)
    {
        while(j!=-1 && t[i]!=t[j]) j = Next[j];
        Next[++i] = ++j;
    }
}

优化的Next

int m,n;
char s[maxn], t[maxm];
int Next[maxm];

void getnext() 
{
    Next[0] = -1;
    int i = 0, j = -1;
    while(i<m)
    {
        while(j!=-1 && t[i]!=t[j]) j = Next[j];
        if(t[++j] == s[++i]) Next[i] = Next[j];
        Next[i] = j;
    }
}

KMP

/*
统计主串中模式串的个数,可以重叠
*/
int kmp() 
{
    int ans = 0;
    getnext();
    int i = 0, j = 0;
    while(i<n)
    {
        while(j!=-1 && s[i]!=t[j]) j = Next[j];
        i++; j++;
        if(j==m)
        {
            ans++;
            j = Next[j]; // 如果要求匹配串不重叠,则 j = 0
        }
    }
    return ans;
}

你可能感兴趣的:(字符串)