<?php
class Trie {
private $_children;
private $_isEnd;
/**
* Initialize your data structure here.
*/
function __construct() {
$this->_children = [];
$this->_isEnd = false;
}
/**
* Inserts a word into the trie.
* @param String $word
* @return NULL
*/
function insert($word) {
$curNode = $this;
for ($i=0,$len=strlen($word); $i<$len; $i++) {
$char = $word[$i];
if (array_key_exists($char, $curNode->_children)) {
$curNode = $curNode->_children[$char];
} else {
$node = new Trie();
$curNode->_children[$char] = $node;
$curNode = $node;
}
}
$curNode->_isEnd = true;
}
/**
* Returns if the word is in the trie.
* @param String $word
* @return Boolean
*/
function search($word) {
$lastNode = $this->getLastNode($word);
return !is_null($lastNode) && $lastNode->_isEnd == true;
}
private function getLastNode($word) {
$curNode = $this;
for ($i=0,$len=strlen($word); $i<$len; $i++) {
$char = $word[$i];
if (!array_key_exists($char, $curNode->_children)) {
return null;
}
$curNode = $curNode->_children[$char];
}
return $curNode;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
* @param String $prefix
* @return Boolean
*/
function startsWith($prefix) {
$lastNode = $this->getLastNode($prefix);
return !is_null($lastNode);
}
}
/**
* Your Trie object will be instantiated and called as such:
* $obj = Trie();
* $obj->insert($word);
* $ret_2 = $obj->search($word);
* $ret_3 = $obj->startsWith($prefix);
*/
$obj = new Trie();
$obj->insert("abc");
06-15
4389
