kmp算法详解php,kmp算法的php实现,可直接执行

/**

* @todo 改进型KMP算法,模式串的移动字符数组

* @param $pattern 模式串

* @param $next 以用模式串的数组

* @author houweizong@gmail.com

* **/

function findNextVal($pattern,&$next){

$next[0] = -1;

$j = 0;

$k = -1;

$length = strlen( $pattern );

while( $j < $length ){

if( $k==-1 || $pattern[$j] == $pattern[$k] ){

$j++;

if( $pattern[$j] == $pattern[$k] ){

$k++;

$next[$j] = $k;

}else{

$k<0 && $k++;

$next[$j] = $next[$k]+1;

}

}else{

$k = $next[$k];

}

}

}

/**

* @todo KMP算法,模式串的移动字符数组

* @param $pattern 模式串

* @param $next 以用模式串的数组

* @author houweizong@gmail.com

* **/

function findNext($pattern,&$next){

$next[0] = -1;

$j = 0;

$k = -1;

$length = strlen( $pattern );

while( $j < $length ){

while( $k > -1 && $pattern[$j] == $pattern[$k] ){

$j++;

$k++;

if($j==$length) break;

$next[$j]=$k;

}

if($k<=0){

$k = 0;

$j+=1;

if($j==$length) break;

$j !=0 && $next[$j] = 0;

}else{

$k = $next[$k];

}

}

}

/**

* @todo kmp算法查找字符串

* @param string @string 目标串

* @param string @pattern 模式串

* @author houweizong@gmail.com

* **/

function kmp($string,$pattern){

$next=array();

findNextVal($pattern,$next);

$ml=strlen($string);

$pl=strlen($pattern);

$i=0;

$j=0;

while($i

while($j==0||$j

$i++;

$j++;

}

if($j==$pl) return $i-$pl;

$j=$next[$j];

}

return -1;

}

$pattern='abshhh';

$string='ababababshhabhshhhabshhhabsabsabs';

$s=kmp($string,$pattern);

var_dump($s);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值