kmp算法模板

t是模式串,s是需要被匹配的串。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 100000;
int nextval[maxn];
void get_next(char* T)
{
    int i = 1, j = 0;
    nextval[1] = 0;
    int len = strlen(T+1);
    while(i < len)
    {
        if(j == 0 || T[i] == T[j])
        {
            ++i;
            ++j;
            if(T[i] == T[j])
                nextval[i] = nextval[j];
            else 
                nextval[i] = j;
        }
        else 
            j = nextval[j];
    }
}
int kmp(char* T, char* S)
{
    int lent = strlen(T+1), lens = strlen(S+1);
    int i = 1, j = 1;
    while(i <= lens && j <= lent)
    {
        if(j == 0 || S[i] == T[j])
        {
            ++i;
            ++j;
        }
        else 
            j = nextval[j];
    }
    if(j > lent)
        return i - lent;
    return 0;
}
int main()
{
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    char t[maxn], s[maxn];
    scanf("%s", t + 1);
    scanf("%s", s + 1);
    memset(nextval, 0, sizeof(nextval));
    get_next(t);
    int pos = kmp(t, s);
    printf("pos = %d\n", pos);
}
posted @ 2019-10-08 17:34  DIY-Z  阅读(115)  评论(0编辑  收藏  举报