kmp算法模板

僤鯓⒐⒋嵵緔 提交于 2019-11-30 19:10:49
#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);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!