码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Implement Trie (Prefix Tree)

时间:2015-07-07 14:34:59      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

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, tmp;
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     if(tree.isWord){
47         return true;
48     }else{
49         return false;
50     }
51 };
52 
53 /**
54  * @param {string} prefix
55  * @return {boolean}
56  * Returns if there is any word in the trie
57  * that starts with the given prefix.
58  */
59 Trie.prototype.startsWith = function(prefix) {
60     var tree = this.root;
61     for(var i = 0; i < prefix.length; i++){
62         if(!tree[prefix[i]]){
63             return false;
64         }
65         tree = tree[prefix[i]];
66     }
67     return true;
68 };

 

 

 

 
 

[LeetCode][JavaScript]Implement Trie (Prefix Tree)

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4626730.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!