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){

	}
}
相关推荐
业精于勤的牙4 小时前
浅谈:算法中的斐波那契数(二)
算法·职场和发展
陈文锦丫4 小时前
MQ的学习
java·开发语言
乌暮4 小时前
JavaEE初阶---线程安全问题
java·java-ee
爱笑的眼睛114 小时前
GraphQL:从数据查询到应用架构的范式演进
java·人工智能·python·ai
不穿格子的程序员4 小时前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表
liuyao_xianhui4 小时前
寻找峰值--优选算法(二分查找法)
算法
dragoooon344 小时前
[hot100 NO.19~24]
数据结构·算法
Seven974 小时前
剑指offer-52、正则表达式匹配
java
代码or搬砖5 小时前
RBAC(权限认证)小例子
java·数据库·spring boot
青蛙大侠公主5 小时前
Thread及其相关类
java·开发语言