首页 > 编程语言 > 详细

kmp算法模板

时间:2019-10-08 18:39:20      阅读:85      评论:0      收藏:0      [点我收藏+]

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);
}

kmp算法模板

原文:https://www.cnblogs.com/KeepZ/p/11636791.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!