|
| 1 | +class TNode { |
| 2 | + isEndOf: boolean; |
| 3 | + children: Map<string, TNode>; |
| 4 | + |
| 5 | + constructor() { |
| 6 | + this.isEndOf = false; |
| 7 | + this.children = new Map<string, TNode>(); |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +class Trie { |
| 12 | + private root: TNode; |
| 13 | + |
| 14 | + constructor() { |
| 15 | + this.root = new TNode(); |
| 16 | + } |
| 17 | + |
| 18 | + insert(word: string): void { |
| 19 | + let currentNode: TNode = this.root; |
| 20 | + |
| 21 | + for (const ch of word) { |
| 22 | + if (currentNode.children.has(ch)) { |
| 23 | + currentNode = currentNode.children.get(ch)!; |
| 24 | + } else { |
| 25 | + const newNode = new TNode(); |
| 26 | + |
| 27 | + currentNode.children.set(ch, newNode); |
| 28 | + currentNode = currentNode.children.get(ch)!; |
| 29 | + } |
| 30 | + } |
| 31 | + currentNode.isEndOf = true; |
| 32 | + } |
| 33 | + |
| 34 | + search(word: string): boolean { |
| 35 | + let currentNode = this.root; |
| 36 | + |
| 37 | + for (const ch of word) { |
| 38 | + if (!currentNode.children.has(ch)) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + currentNode = currentNode.children.get(ch)!; |
| 43 | + } |
| 44 | + |
| 45 | + return currentNode.isEndOf; |
| 46 | + } |
| 47 | + |
| 48 | + startsWith(prefix: string): boolean { |
| 49 | + let currentNode = this.root; |
| 50 | + |
| 51 | + for (const ch of prefix) { |
| 52 | + if (!currentNode.children.has(ch)) { |
| 53 | + return false; |
| 54 | + } |
| 55 | + |
| 56 | + currentNode = currentNode.children.get(ch)!; |
| 57 | + } |
| 58 | + |
| 59 | + return true; |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * Your Trie object will be instantiated and called as such: |
| 65 | + * var obj = new Trie() |
| 66 | + * obj.insert(word) |
| 67 | + * var param_2 = obj.search(word) |
| 68 | + * var param_3 = obj.startsWith(prefix) |
| 69 | + */ |
0 commit comments