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

	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值