PHP-leetcode-208

littlehero發表於2019-09-10
class TrieNode
{
    public $isWord;
    public $childrenMap;

    public function __construct()
    {
        $this->isWord = false;
        $this->childrenMap = [];
    }
}

class Trie
{

    private $root;

    /**
     * Initialize your data structure here.
     */
    function __construct()
    {
        $this->root = new TrieNode();
    }

    /**
     * Inserts a word into the trie.
     * @param String $word
     * @return NULL
     */
    function insert($word)
    {
        $cur = $this->root;
        for ($i = 0; $i < strlen($word); $i++) {
            $c = $word[$i];
            if (!isset($cur->childrenMap[$c])) {
                $cur->childrenMap[$c] = new TrieNode();
            }
            $cur = $cur->childrenMap[$c];
        }
        $cur->isWord = true;
    }

    /**
     * Returns if the word is in the trie.
     * @param String $word
     * @return Boolean
     */
    function search($word)
    {
        $cur = $this->root;
        for ($i = 0; $i < strlen($word); $i++) {
            $c = $word[$i];
            if (!isset($cur->childrenMap[$c])) {
                return false;
            }
            $cur = $cur->childrenMap[$c];
        }
        return $cur->isWord;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     * @param String $prefix
     * @return Boolean
     */
    function startsWith($prefix)
    {
        $cur = $this->root;
        for ($i = 0; $i < strlen($prefix); $i++) {
            $c = $prefix[$i];
            if (!isset($cur->childrenMap[$c])) {
                return false;
            }
            $cur = $cur->childrenMap[$c];
        }
        return true;
    }
}

Runtime: 104 ms, faster than 75.00% of PHP online submissions for Implement Trie (Prefix Tree).
Memory Usage: 40.5 MB, less than 100.00% of PHP online submissions for Implement Trie (Prefix Tree).