嗨,我正在寫一個PHP類來實現Rabin-Karp算法。我有重新哈希部分的問題。此代碼不包含匹配部分字符。由於再次哈希的問題,我不得不停止匹配哈希碼。有人請幫我弄明白。用PHP實現Rabin-Karp算法
<?php
class RabinKarp
{
/**
* @var String
*/
private $pattern ;
private $patternHash ;
private $text ;
private $previousHash ;
/**
* @var Integer
*/
private $radix ;
private $prime ;
private $position ;
/**
* Constructor
*
* @param String $pattern - The pattern
*
*/
public function __construct($pattern)
{
$this->pattern = $pattern;
$this->radix = 256;
$this->prime = 100007;
$this->previousHash = "";
$this->position = 0;
$this->patternHash = $this->generateHash($pattern);
}
private function generateHash($key)
{
$charArray = str_split($key);
$hash = 0;
foreach($charArray as $char)
{
$hash = ($this->radix * $hash + ord($char)) % $this->prime;
}
return $hash;
}
public function search($character)
{
$this->text .= $character;
if(strlen($this->text) < strlen($this->pattern))
{
return false;
}
else
{
$txtHash = 0;
echo $this->previousHash . "<br/>";
if(empty($this->previousHash))
{
$txtHash = $this->generateHash($this->text);
$this->previousHash = $txtHash;
$this->position = 0;
}
else
{
// The issue is here
$charArray = str_split($this->text);
$txtHash = (($txtHash + $this->prime) - $this->radix * strlen($this->pattern) * ord($charArray[$this->position]) % $this->prime) % $this->prime;
$txtHash = ($txtHash * $this->radix + ord($character)) % $this->prime;
$this->previousHash = $txtHash;
}
if($txtHash == $this->patternHash)
{
echo "Hash Match found";
}
}
}
}
$x = new RabinKarp("ABC");
$x->search("Z");
$x->search("A");
$x->search("B");
$x->search("C");
?>
謝謝。
此算法是否適用於多字節字符串值?如果是這樣,你應該使用'mb_'函數來分割長度。 – 2012-03-26 12:15:35
這個算法寫入串行傳輸工作。比方說,你一次獲得一個角色。一旦我收到這個角色,我就開始搜索。上面的代碼適合我。唯一的問題是重新哈希部分。實際上重新哈希值是不正確的。 – 2012-03-26 12:21:45
@PrasadRajapaksha嗨Prasad先生..請你張貼固定代碼。我正在尋找rabin karp算法實現多重模式的php。請...提前致謝 – Ayuktia 2016-06-13 17:46:59