<?php include "TireNode.php"; class Tire { private $root; public function __construct() { $this->root = new TireNode("/");//根节点 } public function getRoot(){ return $this->root; } public function insert($text){ //拿到根节点 $p = $this->root; //遍历字母,对比节点的子节点是否存在,如果不存在,则给当前节点增加对应子节点,并把当前子节点设置为当前节点 for($i=0;$i<strlen($text);$i++){ $index = $data = $text[$i]; if(empty($p->children[$index])){ $newNode = new TireNode($data); $p->children[$index] = $newNode; } $p = $p->children[$index]; } //当遍历结束,当前节点就是最终字符节点 $p->isEndingChar = true; } public function find($pattern){ //拿到根节点 $p = $this->root; //遍历字母,对比子节点是否存在,如果不存在直接返回false,如果遍历完了,判断当前节点是否最终字符节点,如果是返回true,否则返回false for($i=0;$i<strlen($pattern);$i++){ $index = $pattern[$i]; if(empty($p->children[$index])){ return false; } $p = $p->children[$index]; } return $p->isEndingChar; } } $tire = new Tire(); $strings = ['a','apple','btree','newwork','bugs','but','bugsling']; foreach($strings as $string){ $tire->insert($string); } $test_words = ['a','app','btree','newwor','bugs','but1']; foreach($test_words as $word){ $is_contain = $tire->find($word); if($is_contain){ echo $word.'被包含'; }else{ echo $word.'不被包含'; } } //print_r($tire->getRoot());
前缀树PHP实现2
最新推荐文章于 2021-08-06 10:28:52 发布