- #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;
- }
http://blog.csdn.net/liuzhanchen1987/article/details/7931715