大家好,我是 17。

字典树使用场景

  1. 把很多英文单词存入Trie树中。
  2. 建好树后,可以根据用户输入的部分单词推测用户想要输入的完整单词。
  3. 断词和拼写查错软件也运用了Trie

它的优点是最大限度的减少无谓的字符串比较,查询效率比哈希表高。

var Trie = function () {
  this.data = {}
 }
  /**
   * @param {string} word
   * @return {void}
   */
  Trie.prototype.insert = function (word) {
    let node = this.data
    for (let c of word) {
      if (node[c]) {
        node = node[c]
      }
      else {
        node[c] = {}
        node=node[c]
      }
    }
    node['isEnd'] = true
  };

  /**
   * @param {string} word
   * @return {boolean}
   */
  Trie.prototype.search = function (word) {
    let node=this.data
    for (let c of word) {
      node=node[c]
      if (!node) return false

    }
    return  !!node['isEnd']
  };

  /**
   * @param {string} prefix
   * @return {boolean}
   */
  Trie.prototype.startsWith = function (prefix) {
    let node=this.data
    for (let c of prefix) {
      node=node[c]
      if (!node) return false
    }
    return true
  };
}