60、PHP 实现 单词查找树算法

题目: PHP 实现 单词查找树算法

描述:

php 复制代码
class TrieST
{
	private $_root=null;

    /**
     *查找单词$key
     * 
     */
	public function search(string $key){
		 $node=$this->_search($this->_root,$key,0);
		 if(is_null($node)){
		 	return null;
		 }
		 return $node->getVal();
	}

	private function _search($node,string $key,int $keyIndex){
		if(is_null($node)){
			return null;
		}
		if(strlen($key)==$keyIndex){
			return $node;
		}
		$nextNodePos=$key[$keyIndex];
		return $this->_search($node->getNextNode($nextNodePos),$key,++$keyIndex);
	}

    /**
     * 添加单词
     * @param string key 要添加的单词
     */
	public function put(string $key,$value){
		if(is_null($this->_root)){
			$this->_root=$this->_put($this->_root,$key,$value,0);
		}
		$this->_put($this->_root,$key,$value,0);
	}

	private function _put($node,string $key,$value,int $keyIndex){
		if(is_null($node)){
			$node=new Node();
		}
		if(strlen($key)==$keyIndex){
			$node->setVal($value);
			return $node;
		}
        
        $nextNodePos=$key[$keyIndex];
        $nextNode=$this->_put($node->getNextNode($nextNodePos),$key,$value,++$keyIndex);
		$node->setNextNode($nextNodePos,$nextNode);
		return $node;
	}

	public function keyWithPrefix(string $pre){

	}
}
相关推荐
小月土星几秒前
JavaScript 快速排序:从 pivot、双指针到分治思想
javascript·算法·面试
小月土星7 分钟前
JavaScript 递归入门:从 1 到 n 求和,再到数组扁平化
javascript·算法·面试
用户298698530149 分钟前
Java 实现 Word 文档文本与图片提取的方法
java·后端
SimonKing1 小时前
铁子,IntelliJ IDEA 2026.1.3来了,升不升?
java·后端·程序员
咖啡八杯12 小时前
GoF设计模式——策略模式
java·后端·spring·设计模式
To_OC15 小时前
LC 1 两数之和:面试第一道必考题,暴力解法直接被面试官 pass
javascript·算法·leetcode
用户1285261160220 小时前
我把祖传Java项目重构后,接口响应从3s砍到了200ms,只改了这几行代码
java
鱼鱼不愚与20 小时前
《原来如此 | 第01期:为什么导航软件能预测红绿灯倒计时?》
算法