我在GitHub上搜索Bloom Filter时遇到了这个简单的PHP类,它被命名为“Bloom Filter”,但我认为它更像是一个“哈希表”,我好奇的是它很容易理解。PHP哈希键阵列
它读入一个单词文件并为每个单词创建一个散列数组键,然后可以检查散列数组中是否存在该单词。
我很好奇,虽然有没有使用这个的任何好处,只是将实际的单词存储为数组键或值,然后检查该单词是否存在于数组中,理论上这只会增加开销并做同样的事情事情,请帮助我了解我失踪了什么?
<?php
class Dictionary {
private $words;
private $wordsHash;
public $hashLength;
public function __construct($filepath, $hashLength) {
$this->words = file($filepath);
$this->hashLength = $hashLength;
foreach($this->words as $word){
$this->wordsHash[$this->createHash($word)] = true;
}
echo 'words: ' . count($this->words) . ' hashes: ' . count($this->wordsHash) . "\n";
}
public function createHash($str){
$hash = substr(md5(trim($str)), 0, $this->hashLength);
return $hash;
}
public function checkDictionary($str){
$hash = $this->createHash(trim($str));
if(array_key_exists ($hash , $this->wordsHash)){
return true;
}
return false;
}
}
?>
dictionary.txt文件中有10000个字,我将只显示演示几个
der
die
und
in
den
von
zu
das
mit
sich
des
auf
für
ist
用法示例:
<?php
$dictionary = new Dictionary('dictionary.txt', 30);
if($dictionary->checkDictionary('den')){
echo 'The Word den Exist in the Hash Table';
}else{
echo 'The Word den DOES NOT Exist in the Hash Table';
}
?>
在我看来,你可以用普通的PHP数组来做这件事,就像散列一样行事 – hackartist
@hackartist:那就是我在想什么,但我觉得必须有一个理由让人经历了这个麻烦? – JasonDavis