Chinaunix

标题: php 实现KMP算法 [打印本页]

作者: cu_Cbear    时间: 2011-10-25 16:35
标题: php 实现KMP算法
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.    }
复制代码

作者: 如果有一天21    时间: 2011-10-27 10:43
谢谢分享...




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2