字符串匹配问题(KMP算法)

来源:互联网 发布:用mac怎么下游戏 编辑:程序博客网 时间:2024/06/15 05:24

[cpp] view plaincopy
  1. #include<iostream>  
  2. #include<string>  
  3. using namespace std;  
  4. #define MAX 10000  
  5. //KMP算法时间复杂度为O(n+m),其中n为str的长度,m为pat的长度  
  6. void kmp(string str,string pat)  
  7. {  
  8.     bool flag=0;  
  9.     int Pi[MAX]={0},q,k=0,i;  
  10.     int length1=str.length();  
  11.     int length2=pat.length();  
  12.     //字符串的预处理  
  13.     //Pi[q]表示第q个字符往前Pi[q]个字符串与开始的Pi[q]个字符串匹配  
  14.     //Pi[q]==0时表示第q个字符与第一个字符不匹配。  
  15.     for(q=1;q<length2;q++)  
  16.     {  
  17.         while(k>0&&pat[k]!=pat[q])  
  18.         {  
  19.             k=Pi[k];  
  20.         }  
  21.         if(pat[k]==pat[q])  
  22.         {  
  23.             k+=1;  
  24.         }  
  25.         Pi[q]=k;  
  26.     }  
  27.     q=0;  
  28.     for(i=0;i<length1;i++)  
  29.     {  
  30.         //遇到不匹配时只需从pat的第Pi[q-1]个字符与str的第i个字符比较即可  
  31.         while(q>0&&str[i]!=pat[q])  
  32.         {  
  33.             q=Pi[q-1];  
  34.         }  
  35.         if(str[i]==pat[q])  
  36.         {  
  37.             q=q+1;  
  38.         }  
  39.         if(q==length2)  
  40.         {  
  41.             flag=1;  
  42.             cout<<"math occurs with "<<i-length2+1<<endl;  
  43.             q=Pi[q-1];  
  44.         }  
  45.     }  
  46.     if(!flag)  
  47.     {  
  48.         cout<<"there is no math!"<<endl;  
  49.     }  
  50. }  
  51. //普通的字符串匹配时间复杂度为O(n*m)  
  52. void CommenCMath(string s1,string s2)  
  53. {  
  54.     bool flag=0;  
  55.     int length1=s1.length();  
  56.     int length2=s2.length();  
  57.     int i,j;  
  58.     for(i=0;i<=length1-length2;i++)  
  59.     {  
  60.         for(j=0;j<length2;j++)  
  61.         {  
  62.             if(s1[i+j]!=s2[j])  
  63.             {  
  64.                 break;  
  65.             }  
  66.         }  
  67.         if(j==length2)  
  68.         {  
  69.             cout<<"the location is "<<i+1<<endl;  
  70.             flag=1;  
  71.         }  
  72.     }  
  73.     if(!flag)  
  74.     {  
  75.         cout<<"there is no math link charater !"<<endl;  
  76.     }  
  77. }  
  78.   
  79. int main()  
  80. {  
  81.     string st1,st2;  
  82.     cout<<"st1"<<endl;  
  83.     cin>>st1;  
  84.     cout<<endl;  
  85.     cout<<"st2"<<endl;  
  86.     cin>>st2;  
  87. //  CommenCMath(st1,st2);  
  88.     kmp(st1,st2);  
  89.     cout<<endl;  
  90.     return 0;  
  91. }  


http://blog.csdn.net/liuzhanchen1987/article/details/7931715

0 0
原创粉丝点击