-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path208_Trie.js
More file actions
62 lines (55 loc) · 1.18 KB
/
Copy path208_Trie.js
File metadata and controls
62 lines (55 loc) · 1.18 KB
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
/**
* https://leetcode.cn/problems/implement-trie-prefix-tree
*
* 实现 Trie 树
*
* apple
* root
* a
* p
* p
* l
* e, isWord: true
*/
class Trie {
constructor() {
this.root = {};
}
insert(word) {
let node = this.root;
for (const ch of word) {
if (node[ch] == void(0)) {
node[ch] = {};
}
node = node[ch];
}
node.isWord = true;
}
_traverse(word) {
let node = this.root;
for (const ch of word) {
node = node[ch];
if (!node) return null;
}
return node;
}
search(word) {
const node = this._traverse(word);
return !!node && !!node.isWord;
}
startsWith(prefix) {
const node = this._traverse(prefix);
return !!node;
}
}
// ---- test case ----
var trie = new Trie()
trie.insert("apple")
console.log(JSON.stringify(trie));
console.log(trie.search("bbb"))
console.log(trie.search("apple")) // 返回 true
console.log(trie.search("app")) // 返回 false
console.log(trie.startsWith("app")) // 返回 true
console.log(trie.startsWith("apbbb")) // 返回 false
trie.insert("app")
console.log(trie.search("app")) // 返回 true