字符串——可重叠以及不可重叠的子串查找(kmp)

next[i]:字符串a中以a[i]结尾的后缀子串与前缀子串的最大匹配长度。

1 2 3 4 5 6 7 8
a b c a b c m a
0 0 0 1 2 3 0 1 

可重叠代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
typedef unsigned long long ull;
const int N=1e6+10;
char a[N],b[N];
int next1[N];
int n,m;
int f[N];
void get()
{
    next1[1]=0;          
    int j=0;
    for(int i=2;i<=n;i++)
    {
        while(j>0&&a[i]!=a[j+1]) j=next1[j];
        if(a[i]==a[j+1]) j++;
        next1[i]=j;
    }
}
int main()
{
    while(cin>>b+1>>a+1)//从1开始
    {
        int cnt=0;
        n=strlen(a+1);
        m=strlen(b+1);
        get();
        int j=0;
        for(int i=1;i<=m;i++)
        {
            while(j&&(b[i]!=a[j+1])) j=next1[j];
            if(b[i]==a[j+1]) j++;
            if(j==n)//完整出现一次就记录一次,同时把长度回溯
                cnt++,j=next1[j];
        }
        cout<<cnt<<endl;
    }
        return 0;
}

查找的字串不可以重叠的话就把上面代码里面的

cnt++,j=next1[[j]; 改为 cnt++,j=0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值