KMP算法c++实现

10 篇文章 2 订阅

一、原理看下面视频

http://baidu.ku6.com/watch/1196605033445674118.html?page=videoMultiNeed


二、c++代码:

#include<iostream>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;

void get_next(string s1, int next[]){
    int len = s1.size();
    next[0] = 0;
    int i=1;
    int j=0;
    while(i<len){
        if(s1[i] == s1[j]){
            next[i] = j+1;
            i++;
            j++;
        }else{
            while(j>0 && s1[i]!=s1[j]){
                j = next[j-1];
            }
            if(s1[i] == s1[j]){
                next[i] = j+1;
                i++;
                j++;
            }else if(j == 0 && s1[i] != s1[j]){
                next[i] = 0;
                i++;
            }
        }
    }

}

bool kmpAlgorithm(string s1, string s2, int next[]){
    //s1是主串,求s2是否能在s1中模糊匹配出来
    int len1 = s1.size();
    int len2 = s2.size();
    //next的长度和s2的长度是一样的
    int j=0;  //i用来遍历s1,j用来遍历s2

    for(int i=0;i<len1;i++){
        while(j>0 && s1[i]!= s2[j]){
            j = next[j];
        }
        if(s1[i] == s2[j]){
            j++;
        }
        if(j == len2){
            return true;
        }
    }

    return false;
}



int main(){
    string s1,s2;
    while(cin>>s1>>s2){
        //s1是主串,s2是要判断的串
        int *next = new int[s2.size()+1];
        get_next(s2, next);
        cout<<s1<<endl;
        cout<<s2<<endl;
        cout<<kmpAlgorithm(s1, s2, next)<<endl;
    }

    return 0;
}

next数组的测试用例

s字符串: aabaabaaa

next数组:010123452

s字符串:abcaby

next数组:000120

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值