zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree)

    Implement a trie with insertsearch, and startsWith methods.

    https://leetcode.com/problems/implement-trie-prefix-tree/


    实现字典树,每个节点至多有26个子孙,代表26个字母。

    每个节点都有三个属性,key, isWord以及字典(哈希表,提高访问速度,也可以用数组),因为JS可以扩展实例化的对象,直接用下标访问对象,不需要再建一个哈希表了。

    root节点没有key和isWord,剩下的节点key记录该节点的值。

    isWord:比如单词为"tree","tre" -> 不是单词, "tree" -> 是单词。

    构造完字典后,比如要查找"tree",只需要这样访问:root['t']['r']['e']['e'].isWord,任意一步拿不到就说明单词不在字典中。

     1 /**
     2  * @constructor
     3  * Initialize your data structure here.
     4  */
     5 var TrieNode = function(key) {
     6     return {
     7         key : key,  
     8         isWord : false
     9     };
    10 };
    11 
    12 var Trie = function() {
    13     this.root = TrieNode('root');
    14 };
    15 
    16 /**
    17  * @param {string} word
    18  * @return {void}
    19  * Inserts a word into the trie.
    20  */
    21 Trie.prototype.insert = function(word) {
    22     var tree = this.root, i, curr;
    23     for(i = 0; i < word.length; i++){
    24         curr = word[i];
    25         if(!tree[curr]){
    26             tree[curr] = new TrieNode(curr);
    27         }
    28         tree = tree[curr];
    29     }
    30     tree.isWord = true;
    31 };
    32 
    33 /**
    34  * @param {string} word
    35  * @return {boolean}
    36  * Returns if the word is in the trie.
    37  */
    38 Trie.prototype.search = function(word) {
    39     var tree = this.root;
    40     for(var i = 0; i < word.length; i++){
    41         if(!tree[word[i]]){
    42             return false;
    43         }
    44         tree = tree[word[i]];
    45     }
    46     return tree.isWord ? true : false;
    47 };
    48 
    49 /**
    50  * @param {string} prefix
    51  * @return {boolean}
    52  * Returns if there is any word in the trie
    53  * that starts with the given prefix.
    54  */
    55 Trie.prototype.startsWith = function(prefix) {
    56     var tree = this.root;
    57     for(var i = 0; i < prefix.length; i++){
    58         if(!tree[prefix[i]]){
    59             return false;
    60         }
    61         tree = tree[prefix[i]];
    62     }
    63     return true;
    64 };
     
     
  • 相关阅读:
    Eclipse 快捷键
    计算机网络之读Internet网发展史 读后感
    计算机网络之读Internet网发展史 读后感
    动态加载布局的技巧
    二、JSP的3个编译指令,7个动作指令,9个内置对象
    【杭电】[2050]折线分割平面
    【杭电】[2050]折线分割平面
    【杭电】[2068]RPG的错排
    【杭电】[2068]RPG的错排
    【杭电】[4500]小Q系列故事——屌丝的逆袭
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4626730.html
Copyright © 2011-2022 走看看