KMP算法

算法模板

//Author LJH
//www.cnblogs.com/tenlee
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#define clc(a, b) memset(a, b, sizeof(a))
using namespace std;

const int inf = 0x3f;
const int INF = 0x3f3f3f3f;
const int maxn = 5e6+5;

char par[maxn], son[maxn];
int next[maxn];

void get_next()
{
    int len = strlen(son);
    next[0] = next[1] = 0; 
    for(int i = 1; i < len; i++)
    {
        int j = next[i];
        while(j && son[i] != son[j]) j = next[j];
        next[i+1] = son[i] == son[j] ? j+1 : 0;
    }
}
void kmp()
{
    get_next();

    int nu = 0;
    int nlen = strlen(par), mlen = strlen(son);
    int i = 0, j = 0;
    for(i = 0; par[i]; i++)
    {
        while(j && par[i] != son[j])
        {
            j = next[j];
        }
        if(par[i] == son[j]) 
        {
            j++;
        }
        if(j == mlen)
        {
            printf("case %d#  %d\n", ++nu, i - mlen + 1);
            j = 0;
        }
    }
}

int main()
{
    while(true)
    {
        gets(son);
        gets(par);
        kmp();
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/tenlee/p/4593558.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值