|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/design-add-and-search-words-data-structure |
| 3 | + */ |
| 4 | +// Using Trie |
| 5 | +class WordDictionary { |
| 6 | + constructor(private root: Record<string, any> = {}) {} |
| 7 | + |
| 8 | + /** |
| 9 | + * T.C. O(L) L: length of a word |
| 10 | + * S.C. O(L) |
| 11 | + */ |
| 12 | + addWord(word: string): void { |
| 13 | + let node = this.root; |
| 14 | + for (const char of word) { |
| 15 | + if (!node[char]) { |
| 16 | + node[char] = {}; |
| 17 | + } |
| 18 | + node = node[char]; |
| 19 | + } |
| 20 | + node['isEnd'] = true; |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * T.C. O(N) - there are only 2 dots in the word(26 * 26 * N) |
| 25 | + * S.C. O(N * L) N: number of words, L: length of a word |
| 26 | + */ |
| 27 | + search(word: string): boolean { |
| 28 | + return this.dfs(word, this.root); |
| 29 | + } |
| 30 | + |
| 31 | + private dfs(word: string, node: Record<string, any>): boolean { |
| 32 | + for (let i = 0; i < word.length; i++) { |
| 33 | + if (word[i] === '.') { |
| 34 | + for (const key in node) { |
| 35 | + if (this.dfs(word.slice(i + 1), node[key])) { |
| 36 | + return true; |
| 37 | + } |
| 38 | + } |
| 39 | + return false; |
| 40 | + } |
| 41 | + if (!node[word[i]]) { |
| 42 | + return false; |
| 43 | + } |
| 44 | + node = node[word[i]]; |
| 45 | + } |
| 46 | + return !!node['isEnd']; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// Using Array and Set |
| 51 | +class WordDictionary { |
| 52 | + constructor( |
| 53 | + private words: Set<string>[] = Array.from({ length: 25 }, () => new Set()) |
| 54 | + ) {} |
| 55 | + |
| 56 | + /** |
| 57 | + * T.C. O(1) |
| 58 | + * S.C. O(N * L) |
| 59 | + */ |
| 60 | + addWord(word: string): void { |
| 61 | + this.words[word.length - 1].add(word); |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * T.C. O(N * L) N: number of words, L: length of a word |
| 66 | + * S.C. O(1) |
| 67 | + */ |
| 68 | + search(word: string): boolean { |
| 69 | + const hasDot = word.indexOf('.') !== -1; |
| 70 | + const set = this.words[word.length - 1]; |
| 71 | + |
| 72 | + if (!hasDot) { |
| 73 | + return set.has(word); |
| 74 | + } |
| 75 | + |
| 76 | + for (const w of set) { |
| 77 | + let i = 0; |
| 78 | + while (i < word.length) { |
| 79 | + if (word[i] == '.') { |
| 80 | + i++; |
| 81 | + continue; |
| 82 | + } |
| 83 | + if (word[i] !== w[i]) { |
| 84 | + break; |
| 85 | + } |
| 86 | + i++; |
| 87 | + } |
| 88 | + |
| 89 | + if (i === word.length) { |
| 90 | + return true; |
| 91 | + } |
| 92 | + } |
| 93 | + return false; |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +/** |
| 98 | + * Your WordDictionary object will be instantiated and called as such: |
| 99 | + * var obj = new WordDictionary() |
| 100 | + * obj.addWord(word) |
| 101 | + * var param_2 = obj.search(word) |
| 102 | + */ |
0 commit comments