• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php 兑现KMP算法

php 搞代码 3年前 (2022-01-23) 21次浏览 已收录 0个评论

php 实现KMP算法
<?php
/**
* KMP算法的PHP实现
*
* @author zhaojiangwei 2011/10/22 10:28
*/


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

public function KMP($str){
$this->str = str_split($str);
$this->next = array();
}

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

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

while($subIndex = ($substrCount – $subIndex)){
if($subIndex == -1 || $this->str[$strIndex] == $substr[$subIndex]){
$subIn

本文来*源gaodai^.ma#com搞#代!码网
搞gaodaima代码

dex ++;
$strIndex ++;
}else{
$subIndex = $this->next[$subIndex];
}
}

if($subIndex == $substrCount){
return $strIndex – $substrCount;
}else{
return false;
}
}

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

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

$i = 0;
$j = -1;
while($i < $count){
if($j == -1 || $t[$i] == $t[j]){
$j ++;
$i ++;

if($t[$i] == $t[$j]){
$this->next[$i] = $this->next[$j];
}else{
$this->next[$i] = $j;
}
}else{
$j = $this->next[$j];
}
}

return $this->next;
}

}


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php 兑现KMP算法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址