KMP总结

模板


用法

1、求一个串是否是另一个的子串

2、是子串,并有几个子串


代码

int nex[maxn];
string s, b;
void getNext()
{
    int j, k;
    int tlen=b.length();
    j = 0; k = -1; nex[0] = -1;
    while(j < tlen)
        if(k == -1 || b[j] == b[k])
            nex[++j] = ++k;
        else
            k = nex[k];

}

bool kmp()
{
    int ans = 0;
    int i, j = 0;
    int slen=s.length();
    int tlen=b.length();
    if(slen == 1 && tlen == 1)
    {
        if(s[0] == b[0])
            return 1;
        else
            return 0;
    }
    for(i = 0; i < slen&&ans==0; i++) // 求次数只需要将ans=0条件删除即可
    {
        while(j > 0 && s[i] != b[j])
            j = nex[j];
        if(s[i] == b[j])
            j++;
        if(j == tlen)
        {
            ans++;
            j = nex[j];
        }
    }
    if(ans)
    return true;
    return false;
}
View Code
要么优秀要么生锈
原文地址:https://www.cnblogs.com/Superwalker/p/7832073.html