C++实现KMP算法

#include<iostream>
#include<string>
using namespace std;

class Kmp{
    string str;//短小的,需要匹配的字符串
    string text;//长段落的字符串
    int* point_arry;
    int length;//匹配字符串的长度
    public:
    Kmp(string x,string y);
    ~Kmp();
    int* pre_arry();//计算匹配字符串的前缀表
    void search();
    int calculate(string x);//计算字符串长度
};
Kmp::Kmp(string x,string y){
    this->str=x;
    this->text=y;
}
Kmp::~Kmp(){
    delete [] this->point_arry;
}
int Kmp::calculate(string x){
    int len=0;
    while(x[len]){len++;}
    return len;
}
int* Kmp::pre_arry(){
    string x=this->str;
    int len=calculate(x);
    int c=0;
    int i=1;
    this->length=len;
    this->point_arry=new int[len];
    this->point_arry[0]=0;
    while(i<=len-1)
    {
        if(i<len-1){
            if(x[i]==x[c]){
                this->point_arry[i]=++c;
                i++;
            }
            else{
                this->point_arry[i]=0;
                i++;
                c=0;
            }
        }
        if(i==len-1){
            if(x[i]==x[c]){
                this->point_arry[i]=c+1;
                i++;
            }
            else
            {   
                while(--c>=0){
                   if(x[i]==x[this->point_arry[c]]){
                       this->point_arry[i]=this->point_arry[this->point_arry[c]]+1;
                       break;
                   } 
                }
                if(c<0){this->point_arry[i]=0;}
                i++;
            } 
        }
    }
    return this->point_arry;
}
void Kmp::search(){
    int* temp=pre_arry();
    int pre_arry[this->length];
    pre_arry[0]=-1;
    for(int i=0;i<this->length-1;i++){
        pre_arry[i+1]=temp[i];
    }//匹配前,对前缀表进行处理

    int n=this->length;
    int m=calculate(this->text);

    int i=0;
    int j=0;
    while(i<m){
        if(j==n-1 && this->text[i]==this->str[j]){
            cout<<"Found str at "<<i-j<<endl;
            j=pre_arry[j];
        }
        if(this->text[i]==this->str[j]){
            i++;j++;
        }
        else{
            j=pre_arry[j];
            if(j==-1){i++;j++;}
        }
    }  
}

int main(){
    Kmp k("ababcaba","qweababcabapoiababcaba");
    k.search();  
    return 0;
}

以上代码请使用g++编译器,进行编译。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值