kmp算法

来源:互联网 发布:零基础学python张志强 编辑:程序博客网 时间:2024/06/06 18:09
#include<iostream>
#include<string>


using namespace std;


int next[100];


void getNext(string tem){
int len = tem.length();
int k=-1;
int j=0;
next[0]=-1;
while( j<len-1 ){
if( k==-1 || tem[k]==tem[j]){
next[++j]=++k;
}else{
k=next[k];
}
}
}


int kmp(string tem, string str){
getNext(tem);
int lenTem = tem.length();
int lenStr = str.length();
int i=0,j=0;
while( i<lenTem && j<lenStr ){
if(-1==i || tem[i]==str[j]){
i++;
j++;
}else{
i=next[i];
}
}
if(i==lenTem){
return j-i;
}
return -1;
}


int main(){
string tem = "abbcabb";
string str = "xxxxabbcababbcabb";
for(int i=0; i<=tem.length(); ++i){
cout<<next[i]<<" ";
}
cout<<endl;
cout<<kmp(tem,str)<<endl;

return 0;
}
0 0
原创粉丝点击