免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3228 | 回复: 1
打印 上一主题 下一主题

php 实现KMP算法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-10-25 16:35 |只看该作者 |倒序浏览
php 实现KMP算法
  1. <?php
  2.     /**
  3.      * KMP算法的PHP实现
  4.      *
  5.      * @author zhaojiangwei 2011/10/22 10:28
  6.      */

  7. Php代码  
  8. 1.  

  9.     class KMP{
  10.         private $next = NULL; //模式串T的next数组
  11.         private $t = NULL; //模式串
  12.         private $str = NULL; //主串

  13.         public function KMP($str){
  14.             $this->str = str_split($str);
  15.             $this->next = array();
  16.         }

  17.         //返回主串的长度
  18.         public function getStrCount(){
  19.             return count($this->str);
  20.         }

  21.         //返回结果
  22.         public function getStrPos($substr){
  23.             $substr = str_split($substr);
  24.             $this->getNext($substr);
  25.             $strCount = $this->getStrCount();
  26.             $substrCount = count($substr);
  27.             $subIndex = 0;//子串的起始比较位置
  28.             $strIndex = 0;//主串目前的比较到的位置

  29.             while($subIndex < $substrCount && ($strCount - $strIndex) >= ($substrCount - $subIndex)){
  30.                 if($subIndex == -1 || $this->str[$strIndex] == $substr[$subIndex]){
  31.                     $subIndex ++;
  32.                     $strIndex ++;
  33.                 }else{
  34.                     $subIndex = $this->next[$subIndex];
  35.                 }
  36.             }

  37.             if($subIndex == $substrCount){
  38.                 return $strIndex - $substrCount;
  39.             }else{
  40.                 return false;
  41.             }
  42.          }

  43.          //求模式串的NEXT数组
  44.          public function getNext($t){
  45.             if(!is_array($t)){
  46.                 $t = str_split($t);
  47.             }

  48.             $this->next[0] = -1;
  49.             $count = count($t);

  50.             $i = 0;
  51.             $j = -1;
  52.             while($i < $count){
  53.                 if($j == -1 || $t[$i] == $t[j]){
  54.                     $j ++;
  55.                     $i ++;
  56.                     
  57.                     if($t[$i] == $t[$j]){
  58.                         $this->next[$i] = $this->next[$j];
  59.                     }else{
  60.                         $this->next[$i] = $j;
  61.                     }
  62.                 }else{
  63.                     $j = $this->next[$j];
  64.                 }
  65.             }

  66.             return $this->next;
  67.         }

  68.    }
复制代码

论坛徽章:
0
2 [报告]
发表于 2011-10-27 10:43 |只看该作者
谢谢分享...
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP