#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++编译器,进行编译。