-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplementTrie.js
More file actions
94 lines (83 loc) · 1.94 KB
/
implementTrie.js
File metadata and controls
94 lines (83 loc) · 1.94 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
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
/**
* LeetCode 208. Implement Trie (Prefix Tree)
* https://leetcode.com/problems/implement-trie-prefix-tree/
*
* A trie (pronounced as "try") or prefix tree is a tree data structure used to
* efficiently store and retrieve keys in a dataset of strings. There are
* various applications of this data structure, such as autocomplete and
* spellchecker.
*
* Implement the Trie class:
*
* - Trie() Initializes the trie object.
* - void insert(String word) Inserts the string word into the trie.
* - boolean search(String word) Returns true if the string word is in the trie
* (i.e., was inserted before), and false otherwise.
* - boolean startsWith(String prefix) Returns true if there is a previously
* inserted string word that has the prefix prefix, and false otherwise.
*/
/*
class Trie {
constructor() {
this.list = [];
}
insert(word) {
this.list.push(word);
}
search(word) {
return this.list.includes(word);
}
startsWith(prefix) {
return this.list.some((word) => word.startsWith(prefix));
}
}
*/
class TrieNode {
constructor() {
this.children = {};
this.isEnd = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
/**
* @param {string} word
* @return {void}
*/
insert(word) {
let node = this.root;
for (const ch of word) {
if (!node.children[ch]) {
node.children[ch] = new TrieNode();
}
node = node.children[ch];
}
node.isEnd = true;
}
/**
* @param {string} word
* @return {boolean}
*/
search(word) {
const node = this._traverse(word);
return node?.isEnd ?? false;
}
/**
* @param {string} prefix
* @return {boolean}
*/
startsWith(prefix) {
return this._traverse(prefix) !== null;
}
_traverse(str) {
let node = this.root;
for (const ch of str) {
if (!node.children[ch]) return null;
node = node.children[ch];
}
return node;
}
}
module.exports = { Trie };