KMP

 

这里不做研究,只是为个人加深印象而写,以便日后查阅,具体可以参考下面两篇文章,写的比较详细:

http://wenku.baidu.com/view/5045c90cba1aa8114431d994.html

http://www.matrix67.com/blog/archives/115

C++代码

 

  1. #include<iostream>  
  2.   
  3. //获取模式数组  
  4. void GetNext(const char* p,int next[])  
  5. {  
  6.     int m=0;  
  7.     int n=-1;  
  8.     next[0] = -1;  
  9.     while (p[m+1] != '/0')  
  10.     {  
  11.         if (n==-1 || p[m]==p[n])  
  12.         {  
  13.             ++m;  
  14.             ++n;  
  15.             if (p[m]!=p[n])  
  16.                 next[m] = n;  
  17.             else  
  18.                 next[m]=next[n];  
  19.         }  
  20.         else  
  21.         {  
  22.             n = next[n];  
  23.         }  
  24.     }  
  25. }  
  26.   
  27. //查找匹配位置  
  28. int KMP(const char* pSchar,const char* pDchar,int pos)  
  29. {  
  30.     int i = pos;  
  31.     int j = 0;  
  32.     int index = 0;  
  33.     int* next = new int[strlen(pDchar)+1];  
  34.     GetNext(pDchar,next);  
  35.     while(pSchar[i] != '/0' && pDchar[j] != '/0')  
  36.     {  
  37.         if (pSchar[i] == pDchar[j])  
  38.         {  
  39.             ++i;  
  40.             ++j;  
  41.         }  
  42.         else  
  43.         {  
  44.             index += j - next[j];  
  45.             if (next[j] != -1)  
  46.                 j = next[j];  
  47.             else  
  48.             {  
  49.                 j = 0;  
  50.                 ++i;  
  51.             }  
  52.         }  
  53.     }  
  54.     delete[] next;  
  55.     if (pDchar[j] == '/0')  
  56.         return index;  
  57.     else  
  58.         return -1;  
  59. }  
  60.   
  61. void main()  
  62. {  
  63.   
  64.     char* s = "abababaabab";  
  65.     char* p = "aaba";  
  66.     int index = -1;  
  67.     index = KMP(s,p,0);  
  68.     if (index != -1)  
  69.         printf("从第%d个字符开始匹配",index+1);  
  70.     else  
  71.         printf("%s","没有找到匹配");  
  72. }  

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值