KMP算法自我理解 和 模板

 

字符串   abcd abc abcd abc

匹配串   cdabcd

匹配串的 next  0 0 0 0 1 2;

 开始匹配 

      abcd abc abcd abc

          cd abc d

a,d 匹配失败 

    next 数组进行移动  

    abcd abc abcd abcd

                 c dabcd

    再次匹配

模板

 

这个算法有些问题(尚未找到修改方法)

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int nt[1000];
//  next 数组首位为  0
int KMP(string ss,string tt)
{
    nt[0]=0;
    for(int p=1,k=0;p<tt.size();p++)
    {
        while(k>0 && tt[k]!=tt[p])
            k=tt[k-1];
        if(tt[k]==tt[p])
            k++;
        nt[p]=k;
    }  // 构建 next 数组
    for(int p=1,k=0;p<ss.size();p++)
    {
        while(k>0&& ss[p]!=tt[k])
            k=tt[k-1];
        if(ss[p]==tt[k])
            k++;
        if(k==tt.size())
        {
            cout<<"数组下标开始"<<p-tt.size()+1<<"   "<<p<<endl;
            return 1;
        }
    }
    return 0;
}
int main()
{
    string ss,tt;
    cin>>ss>>tt;
    cout<<KMP(ss,tt)<<endl;
}

next[0]=-1;

 

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int nt[10005];
char tt[1000005];
char ss[1000005];
int KMP()
{
    int s=strlen(ss);  // ss
    int t=strlen(tt);
    nt[0]=-1;
    int num=0;
    for(int i=0,j=-1;i<s;)
    {
        if(j==-1||ss[i]==ss[j])
        {
            i++; j++;
            nt[i]=j; // next[1]=0;
        }
        else
            j=nt[j];
    }
    //for(int i=0;i<s;i++)
    //cout<<nt[i]<<endl;
    for(int i=0,j=0;i<t;)
    {
        if(j==-1||ss[j]==tt[i])
        {
            i++; j++;
        }
        else j=nt[j];
        if(j==s)
        {
            num++;
            j=0;
        }

    }
    return num;



}
int main()
{

    while(scanf("%s",tt)!=EOF&&tt[0]!='#')
    {
        scanf("%s",ss);
        cout<<KMP()<<endl;
    }
}

 

转载于:https://www.cnblogs.com/Andromeda-Galaxy/p/9734342.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值