剪花布条 【HDU - 2087】【KMP模板题】

KMP教学链接,不懂的可以在线问


题意:

2个字符串A,B.问A中有多少个字符串B.

Input

输入中含有一些数据,分别是成对出现A,B
A和B不会超过1000个字符。
如果遇见#字符,则表示测试结束。
 

Output

输出B的个数,每个结果之间应换行。


KMP模板题:
 

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN=1e3+5;
char a[maxN], b[maxN];
int nex[maxN];
void cal_next(int len)
{
    nex[0]=-1;
    int k = -1;
    for(int i=1; i<len; i++)
    {
        while(k>-1 && nex[k+1]!=b[i])
        {
            k = nex[k];
        }
        if(nex[k+1] == b[i]) k++;
        nex[i]=k;
    }
}
int KMP(int sa, int ea, int len)
{
    int k = -1;
    for(int i=sa; i<ea; i++)
    {
        while(k>-1 && a[i]!=b[k+1])
        {
            k = nex[k];
        }
        if(b[k+1] == a[i]) k++;
        if(k == len-1) return i-len+1;
    }
    return -1;
}
int main()
{
    while(scanf("%s %s", a, b)!=EOF)
    {
        if(a[0]=='#') break;
        int lena=(int)strlen(a), lenb=(int)strlen(b);
        cal_next(lenb);
        int tmp=0, now=0, ans=0;
        while(lena-now>=lenb && (tmp=KMP(now, lena, lenb))!=-1 )
        {
            ans++;
            now = tmp + lenb;
        }
        printf("%d\n", ans);
        getchar();
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值