kmp poj 3461

这是一道KMP的水题,还没明白KMP是怎么回事 ==,先贴了代码,明天继续研究。


#include <stdio.h>
#include <string.h>

const int MaxN = 1000010;
char word[MaxN/10], txt[MaxN];
int next[MaxN/10];

void KMP_next(char b[], int pre[])
{
    int n = (int)strlen(b), k;
    pre[0] = -1; k = -1;
    for(int i = 1; i < n; i++)
    {
        while(k > -1 && b[k+1] != b[i]) k = pre[k];
        if(b[k+1] == b[i]) k++;
        pre[i] = k;
    }
}

int main()
{
    int n;
    for(scanf("%d%*c", &n); n--;)
    {
        gets(word); gets(txt);
        KMP_next(word, next);
        int cnt = 0, len = (int)strlen(word);
        for(int i = 0, j = -1; txt[i]; ++i)
        {
             while(j > -1 && word[j+1] != txt[i])
                 j = next[j];
             if(word[j+1] == txt[i])
                 j++;
             if(j == len-1) {
                 cnt++; j = next[j];
             }
         }
         printf("%d\n", cnt);
     }
     return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值