|
| 1 | +// 3rd tried |
1 | 2 | class TrieNode { |
2 | 3 | children: Map<string, TrieNode>; |
3 | 4 | isEnd: boolean; |
4 | | - |
5 | 5 | constructor() { |
6 | | - this.children = new Map(); |
7 | | - this.isEnd = false; |
| 6 | + this.children = new Map(); |
| 7 | + this.isEnd = false |
8 | 8 | } |
9 | 9 | } |
10 | | - |
11 | 10 | class Trie { |
12 | 11 | root: TrieNode; |
13 | 12 |
|
14 | 13 | constructor() { |
15 | | - this.root = new TrieNode(); |
| 14 | + this.root = new TrieNode(); |
16 | 15 | } |
17 | 16 |
|
18 | 17 | insert(word: string): void { |
19 | | - let node = this.root; |
20 | | - for (const char of word) { |
21 | | - if (!node.children.has(char)) { |
22 | | - node.children.set(char, new TrieNode()); |
| 18 | + let node = this.root; |
| 19 | + for(const ch of word) { |
| 20 | + if(!node.children.has(ch)) { |
| 21 | + node.children.set(ch, new TrieNode()); |
| 22 | + } |
| 23 | + node = node.children.get(ch)! |
23 | 24 | } |
24 | | - node = node.children.get(char)!; |
25 | | - } |
26 | | - node.isEnd = true; |
| 25 | + node.isEnd = true; |
27 | 26 | } |
28 | 27 |
|
29 | 28 | search(word: string): boolean { |
30 | | - const node = this._findNode(word); |
31 | | - return node !== null && node.isEnd; |
| 29 | + let node = this.root; |
| 30 | + for(const ch of word) { |
| 31 | + if(!node.children.has(ch)) return false; |
| 32 | + node = node.children.get(ch)!; |
| 33 | + } |
| 34 | + return node.isEnd; |
32 | 35 | } |
33 | 36 |
|
34 | 37 | startsWith(prefix: string): boolean { |
35 | | - return this._findNode(prefix) !== null; |
36 | | - } |
37 | | - |
38 | | - private _findNode(word: string): TrieNode | null { |
39 | | - let node = this.root; |
40 | | - for (const char of word) { |
41 | | - if (!node.children.has(char)) return null; |
42 | | - node = node.children.get(char)!; |
43 | | - } |
44 | | - return node; |
| 38 | + let node = this.root; |
| 39 | + for(const ch of prefix) { |
| 40 | + if(!node.children.has(ch)) return false; |
| 41 | + node = node.children.get(ch)!; |
| 42 | + } |
| 43 | + return true; |
45 | 44 | } |
46 | 45 | } |
| 46 | + |
| 47 | +/** |
| 48 | +* Your Trie object will be instantiated and called as such: |
| 49 | +* var obj = new Trie() |
| 50 | +* obj.insert(word) |
| 51 | +* var param_2 = obj.search(word) |
| 52 | +* var param_3 = obj.startsWith(prefix) |
| 53 | +*/ |
0 commit comments