208. Implement Trie (Prefix Tree)

Difficulty:
Related Topics:
Similar Questions:

Problem

Implement a trie with insert, search, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

Note:

Solution

var Node = function () {
  this.children = {};
  this.isWord = false;
};

/**
 * Initialize your data structure here.
 */
var Trie = function() {
  this.root = new Node();
};

/**
 * Inserts a word into the trie. 
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function(word) {
  var len = word.length;
  var node = this.root;
  var char = 0;
  for (var i = 0; i < len; i++) {
    char = word[i];
    if (!node[char]) node[char] = new Node();
    node = node[char];
  }
  node.isWord = true;
};

/**
 * Returns if the word is in the trie. 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function(word) {
  var len = word.length;
  var node = this.root;
  var char = 0;
  for (var i = 0; i < len; i++) {
    char = word[i];
    if (!node[char]) return false;
    node = node[char];
  }
  return node.isWord;
};

/**
 * Returns if there is any word in the trie that starts with the given prefix. 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function(prefix) {
  var len = prefix.length;
  var node = this.root;
  var char = 0;
  for (var i = 0; i < len; i++) {
    char = prefix[i];
    if (!node[char]) return false;
    node = node[char];
  }
  return true;
};

/** 
 * Your Trie object will be instantiated and called as such:
 * var obj = Object.create(Trie).createNew()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */

Explain:

nope.

Complexity: