class Trie{
public $tree = array();
public function insert($str){
$count = strlen($str);
$T = &$this->tree;
//关联数组递归各个字符,无则新建
for($i = 0; $i < $count; $i++){
$c = $str[$i];
if (!isset($T[$c]))
$T[$c] = array();
$T = &$T[$c];
}
}
public function remove($chars){
if($this->find($chars)){
$count = strlen($chars);
$T = &$this->tree;
for($i = 0;$i < $count;$i++){
$c = $chars[$i];
if(count($T[$c]) == 1){
unset($T[$c]);
return true;
}
$T = &$T[$c];
}
}
}
public function find($chars){
$count = strlen($chars);
$T = &$this->tree;
//循环遍历各个字符,如无则返回false
for($i = 0;$i < $count;$i++){
$c = $chars[$i];
if(!array_key_exists($c, $T)){
return false;
}
$T = &$T[$c];
}
//否则返回找到
return true;
}
}
$t = new Trie();
$t->insert('str');
var_dump($t->find('str'));
更多:
https://github.com/fran6co/phptrie
http://kaiserleib.com/archives/63
http://www.cnblogs.com/endsock/p/3584161.html
标签:none
第9行 $chars 应该为 $str