|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/design-add-and-search-words-data-structure |
| 3 | + * n: The total number of words stored in the Trie. |
| 4 | + * m: The average length of each word. |
| 5 | + * |
| 6 | + * time complexity: |
| 7 | + * - addWord: O(m) |
| 8 | + * - search: O(26^m) in the worst case (with multiple wildcards) to O(m) in general cases. |
| 9 | + * space complexity: O(n * m) |
| 10 | + */ |
| 11 | +class TrieNode { |
| 12 | + children: Map<string, TrieNode>; |
| 13 | + isEnd: boolean; |
| 14 | + |
| 15 | + constructor() { |
| 16 | + this.children = new Map(); |
| 17 | + this.isEnd = false; |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +export class WordDictionary { |
| 22 | + private root: TrieNode; |
| 23 | + |
| 24 | + constructor() { |
| 25 | + this.root = new TrieNode(); |
| 26 | + } |
| 27 | + |
| 28 | + addWord(word: string): void { |
| 29 | + let node = this.root; |
| 30 | + |
| 31 | + for (const char of word) { |
| 32 | + if (!node.children.has(char)) node.children.set(char, new TrieNode()); |
| 33 | + |
| 34 | + node = node.children.get(char)!; |
| 35 | + } |
| 36 | + node.isEnd = true; |
| 37 | + } |
| 38 | + |
| 39 | + search(word: string): boolean { |
| 40 | + return this.searchInNode(word, 0, this.root); |
| 41 | + } |
| 42 | + |
| 43 | + private searchInNode(word: string, index: number, node: TrieNode): boolean { |
| 44 | + if (index === word.length) return node.isEnd; |
| 45 | + |
| 46 | + const char = word[index]; |
| 47 | + |
| 48 | + if (char === '.') { |
| 49 | + for (const child of node.children.values()) { |
| 50 | + if (this.searchInNode(word, index + 1, child)) return true; |
| 51 | + } |
| 52 | + return false; |
| 53 | + } else { |
| 54 | + if (!node.children.has(char)) return false; |
| 55 | + return this.searchInNode(word, index + 1, node.children.get(char)!); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments