|
| 1 | +function Node() { |
| 2 | + // ๋จ์ด์ ๋์ ์๋ฏธ + ๋ฌด์จ ๋จ์ด์ธ์ง ์ ์ฅ |
| 3 | + this.value = null; |
| 4 | + // ๋จ์ด์ ๋ค์ ๋ฌธ์๋ก ์ฐ๊ฒฐ๋์ด ์๋ ๋
ธ๋๋งต |
| 5 | + this.wordGraph = new Map(); |
| 6 | +} |
| 7 | + |
| 8 | +var WordDictionary = function () { |
| 9 | + this.wordGraph = new Map(); |
| 10 | +}; |
| 11 | + |
| 12 | +/** |
| 13 | + * TC: O(N) |
| 14 | + * SC: O(1) |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {string} word |
| 19 | + * @return {void} |
| 20 | + */ |
| 21 | +WordDictionary.prototype.addWord = function (word) { |
| 22 | + let pointer = this; |
| 23 | + for (const w of word) { |
| 24 | + if (!pointer.wordGraph.has(w)) { |
| 25 | + pointer.wordGraph.set(w, new Node()); |
| 26 | + } |
| 27 | + pointer = pointer.wordGraph.get(w); |
| 28 | + } |
| 29 | + pointer.value = word; |
| 30 | +}; |
| 31 | + |
| 32 | +/** |
| 33 | + * TC: O(D^W) |
| 34 | + * SC: O(D * W) |
| 35 | + * |
| 36 | + * W: word.length, D: count of Dictionary.wordGraph keys |
| 37 | + * |
| 38 | + * ํ์ด: Trie ์๋ฃ๊ตฌ์กฐ + bfsํ์ |
| 39 | + */ |
| 40 | + |
| 41 | +/** |
| 42 | + * @param {string} word |
| 43 | + * @return {boolean} |
| 44 | + */ |
| 45 | +WordDictionary.prototype.search = function (word) { |
| 46 | + const queue = [{ pointer: this, index: 0 }]; |
| 47 | + |
| 48 | + // 1. BFS ํ์ ๋ฐฉ๋ฒ ์ด์ฉ |
| 49 | + while (queue.length > 0) { |
| 50 | + const { pointer, index } = queue.shift(); |
| 51 | + |
| 52 | + // 2. ์ฐพ๊ณ ์ํ๋ ๋จ์ด์ ๋์ ๋๋ฌํ์ผ๋ฉด ํด๋น ๋จ์ด๊ฐ ์๋์ง ํ์ธํ๋ค. |
| 53 | + if (index === word.length) { |
| 54 | + if (pointer.value !== null) { |
| 55 | + return true; |
| 56 | + } |
| 57 | + continue; |
| 58 | + } |
| 59 | + |
| 60 | + if (word[index] === ".") { |
| 61 | + // 3. ์ฐพ๊ณ ์ํ๋ ๋จ์ด์ ๋ฌธ์๊ฐ '.'์ธ ๊ฒฝ์ฐ, ํ์ฌ graph์์ ์ด์ด์ง ๋ฌธ์๋ฅผ ๋ชจ๋ ํ์(queue์ ์ถ๊ฐ) |
| 62 | + for (const [key, node] of pointer.wordGraph) { |
| 63 | + queue.push({ pointer: node, index: index + 1 }); |
| 64 | + } |
| 65 | + } else if (pointer.wordGraph.has(word[index])) { |
| 66 | + // 4. ์ฐพ๊ณ ์ํ๋ ๋จ์ด์ ๋ฌธ์๊ฐ graph์ ์๋ ๊ฒฝ์ฐ ํ์(queue์ ์ถ๊ฐ) |
| 67 | + queue.push({ |
| 68 | + pointer: pointer.wordGraph.get(word[index]), |
| 69 | + index: index + 1, |
| 70 | + }); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + // 5. ๋์ด์ ํ์ํ ๊ฒ์ด ์๋ค๋ฉด ํด๋น ๋จ์ด ์์์ผ๋ก ํ๋จ |
| 75 | + return false; |
| 76 | +}; |
| 77 | + |
| 78 | +/** |
| 79 | + * Your WordDictionary object will be instantiated and called as such: |
| 80 | + * var obj = new WordDictionary() |
| 81 | + * obj.addWord(word) |
| 82 | + * var param_2 = obj.search(word) |
| 83 | + */ |
0 commit comments