-
Notifications
You must be signed in to change notification settings - Fork 130
/
Implement Trie (Prefix Tree).js
109 lines (91 loc) · 2.22 KB
/
Implement Trie (Prefix Tree).js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
*/
/**
* @constructor
* Initialize your data structure here.
*/
// MEMORY LIMIT EXCEEDED
var TrieNode = function() {
var isEnd,
links = {};
return {
containsKey: function(n) {
return links[n] !== undefined;
},
get: function(ch) {
return links[ch];
},
put: function(ch, node) {
links[ch] = node;
},
setEnd: function() {
isEnd = true;
},
isEnd: function() {
return isEnd;
}
};
};
var Trie = function() {
this.root = TrieNode();
};
/**
* @param {string} word
* @return {void}
* Inserts a word into the trie.
*/
Trie.prototype.insert = function(word) {
var len = word.length,
node = this.root,
ch,
i;
for (i = 0; i < len; i++) {
ch = word.charAt(i);
if (!node.containsKey(ch)) {
node.put(ch, TrieNode());
}
node = node.get(ch);
}
node.setEnd();
};
/**
* @param {string} word
* @return {boolean}
* Returns if the word is in the trie.
*/
Trie.prototype.search = function(word) {
var node = this.searchPrefix(word);
return node && node.isEnd();
};
/**
* @param {string} prefix
* @return {boolean}
* Returns if there is any word in the trie
* that starts with the given prefix.
*/
Trie.prototype.startsWith = function(prefix) {
return this.searchPrefix(prefix) !== null;
};
Trie.prototype.searchPrefix = function(prefix) {
var len = prefix.length,
node = this.root,
ch,
i;
for (i = 0; i < len; i++) {
ch = prefix.charAt(i);
if (!node.containsKey(ch)) {
return null;
}
node = node.get(ch);
}
return node;
};
/**
* Your Trie object will be instantiated and called as such:
* var trie = new Trie();
* trie.insert("somestring");
* trie.search("key");
*/arch("theomachia"),search("roughy"),search("hypotarsal"),search("snooze"),search("pronominalize"),search("proselytist"),search("lingel")