|
| 1 | +class TrieNode { |
| 2 | + public children: Map<string, TrieNode>; |
| 3 | + public isEnd: boolean; |
| 4 | + |
| 5 | + constructor() { |
| 6 | + this.children = new Map(); |
| 7 | + this.isEnd = false; |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +class Trie { |
| 12 | + private root: TrieNode; |
| 13 | + |
| 14 | + constructor() { |
| 15 | + this.root = new TrieNode(); |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * TC: O(n) |
| 20 | + * SC: O(n) |
| 21 | + * */ |
| 22 | + insert(word: string): void { |
| 23 | + let node = this.root; |
| 24 | + |
| 25 | + for (const char of word) { |
| 26 | + if (!node.children.has(char)) { |
| 27 | + node.children.set(char, new TrieNode()); |
| 28 | + } |
| 29 | + |
| 30 | + node = node.children.get(char)!; |
| 31 | + } |
| 32 | + |
| 33 | + node.isEnd = true; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * TC: O(n) |
| 38 | + * SC: O(n) |
| 39 | + * */ |
| 40 | + search(word: string): boolean { |
| 41 | + let node = this.root; |
| 42 | + |
| 43 | + for (const char of word) { |
| 44 | + if (!node.children.has(char)) { |
| 45 | + return false; |
| 46 | + } |
| 47 | + |
| 48 | + node = node.children.get(char)!; |
| 49 | + } |
| 50 | + |
| 51 | + return node.isEnd; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * TC: O(n) |
| 56 | + * SC: O(n) |
| 57 | + * */ |
| 58 | + startsWith(prefix: string): boolean { |
| 59 | + let node = this.root; |
| 60 | + |
| 61 | + for (const char of prefix) { |
| 62 | + if (!node.children.has(char)) { |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + node = node.children.get(char)!; |
| 67 | + } |
| 68 | + |
| 69 | + return true; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +/** |
| 74 | + * Your Trie object will be instantiated and called as such: |
| 75 | + * var obj = new Trie() |
| 76 | + * obj.insert(word) |
| 77 | + * var param_2 = obj.search(word) |
| 78 | + * var param_3 = obj.startsWith(prefix) |
| 79 | + */ |
| 80 | + |
| 81 | +const trie = new Trie(); |
| 82 | + |
| 83 | +trie.insert("apple"); |
| 84 | + |
| 85 | +const tc1 = trie.search("apple"); // return True |
| 86 | +console.info("π : tolluset.ts:59: tc1=", tc1); |
| 87 | + |
| 88 | +const tc2 = trie.search("app"); // return False |
| 89 | +console.info("π : tolluset.ts:61: tc2=", tc2); |
| 90 | + |
| 91 | +const tc3 = trie.startsWith("app"); // return True |
| 92 | +console.info("π : tolluset.ts:63: tc3=", tc3); |
| 93 | + |
| 94 | +trie.insert("app"); |
| 95 | + |
| 96 | +const tc4 = trie.search("app"); // return True |
| 97 | +console.info("π : tolluset.ts:66: tc4=", tc4); |
0 commit comments