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

  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值