算法导论第32章——字符串匹配问题(KMP算法)

来源:互联网 发布:电脑围棋打谱软件 编辑:程序博客网 时间:2024/06/05 09:44

下面代码列举了普通字符串匹配算法和KMP算法。KMP算法原理见算法导论第32章。代码中有简单的注释可以帮助理解:

#include<iostream>#include<string>using namespace std;#define MAX 10000//KMP算法时间复杂度为O(n+m),其中n为str的长度,m为pat的长度void kmp(string str,string pat){bool flag=0;int Pi[MAX]={0},q,k=0,i;int length1=str.length();int length2=pat.length();//字符串的预处理//Pi[q]表示第q个字符往前Pi[q]个字符串与开始的Pi[q]个字符串匹配//Pi[q]==0时表示第q个字符与第一个字符不匹配。for(q=1;q<length2;q++){while(k>0&&pat[k]!=pat[q]){k=Pi[k];}if(pat[k]==pat[q]){k+=1;}Pi[q]=k;}q=0;for(i=0;i<length1;i++){//遇到不匹配时只需从pat的第Pi[q-1]个字符与str的第i个字符比较即可while(q>0&&str[i]!=pat[q]){q=Pi[q-1];}if(str[i]==pat[q]){q=q+1;}if(q==length2){flag=1;cout<<"math occurs with "<<i-length2+1<<endl;q=Pi[q-1];}}if(!flag){cout<<"there is no math!"<<endl;}}//普通的字符串匹配时间复杂度为O(n*m)void CommenCMath(string s1,string s2){bool flag=0;int length1=s1.length();int length2=s2.length();int i,j;for(i=0;i<=length1-length2;i++){for(j=0;j<length2;j++){if(s1[i+j]!=s2[j]){break;}}if(j==length2){cout<<"the location is "<<i+1<<endl;flag=1;}}if(!flag){cout<<"there is no math link charater !"<<endl;}}int main(){string st1,st2;cout<<"st1"<<endl;cin>>st1;cout<<endl;cout<<"st2"<<endl;cin>>st2;//CommenCMath(st1,st2);kmp(st1,st2);cout<<endl;return 0;}


 

原创粉丝点击