|
| 1 | +// ๊ฐ ๋ฌธ์ ๋
ธ๋๋ฅผ ๋ํ๋ด๋ TrieNode ํด๋์ค |
| 2 | +class TrieNode { |
| 3 | + constructor() { |
| 4 | + this.children = {}; // ์์ ๋
ธ๋๋ค์ ์ ์ฅํ๋ ๊ฐ์ฒด (์: { a: TrieNode, b: TrieNode, ... }) |
| 5 | + this.isEndOfWord = false; // ๋จ์ด๊ฐ ์ด ๋
ธ๋์์ ๋๋๋์ง ์ฌ๋ถ |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +class WordDictionary { |
| 10 | + constructor() { |
| 11 | + this.root = new TrieNode(); // ๋ฃจํธ ๋
ธ๋ ์์ฑ (๋ชจ๋ ๋จ์ด์ ์์์ ) |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * ๋จ์ด๋ฅผ Trie์ ์ถ๊ฐ |
| 16 | + * @param {string} word |
| 17 | + */ |
| 18 | + addWord(word) { |
| 19 | + let node = this.root; |
| 20 | + for (let char of word) { |
| 21 | + // ํ์ฌ ๋ฌธ์๊ฐ ์์ ๋
ธ๋์ ์์ผ๋ฉด ์ ๋
ธ๋ ์์ฑ |
| 22 | + if (!node.children[char]) { |
| 23 | + node.children[char] = new TrieNode(); |
| 24 | + } |
| 25 | + // ๋ค์ ๋ฌธ์๋ก ์ด๋ |
| 26 | + node = node.children[char]; |
| 27 | + } |
| 28 | + // ๋จ์ด๊ฐ ๋๋๋ ์ง์ ํ์ |
| 29 | + node.isEndOfWord = true; |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * ๋จ์ด ๊ฒ์ (.์ ์์ผ๋์นด๋๋ก ์ด๋ค ๋ฌธ์๋ ๋์ฒด ๊ฐ๋ฅ) |
| 34 | + * @param {string} word |
| 35 | + * @returns {boolean} |
| 36 | + */ |
| 37 | + search(word) { |
| 38 | + /** |
| 39 | + * DFS ๋ฐฉ์์ผ๋ก ๊ฒ์์ ์ํ (๋ฐฑํธ๋ํน ํฌํจ) |
| 40 | + * @param {TrieNode} node - ํ์ฌ ๋
ธ๋ |
| 41 | + * @param {number} i - ํ์ฌ ํ์ ์ค์ธ ๋ฌธ์ ์ธ๋ฑ์ค |
| 42 | + */ |
| 43 | + const dfs = (node, i) => { |
| 44 | + // ๋จ์ด ๋์ ๋๋ฌํ๋ฉด isEndOfWord ์ฌ๋ถ ๋ฐํ |
| 45 | + if (i === word.length) { |
| 46 | + return node.isEndOfWord; |
| 47 | + } |
| 48 | + |
| 49 | + const char = word[i]; |
| 50 | + |
| 51 | + // ํ์ฌ ๋ฌธ์๊ฐ '.'์ผ ๊ฒฝ์ฐ ๋ชจ๋ ์์ ๋
ธ๋ ํ์ |
| 52 | + if (char === ".") { |
| 53 | + for (let child of Object.values(node.children)) { |
| 54 | + // ํ๋๋ผ๋ ์ฑ๊ณตํ๋ฉด true ๋ฐํ |
| 55 | + if (dfs(child, i + 1)) return true; |
| 56 | + } |
| 57 | + // ๋ชจ๋ ์์ ๋
ธ๋๊ฐ ์คํจํ๋ฉด false ๋ฐํ |
| 58 | + return false; |
| 59 | + } else { |
| 60 | + // ํด๋น ๋ฌธ์๋ก ์ฐ๊ฒฐ๋ ์์ ๋
ธ๋๊ฐ ์์ผ๋ฉด false |
| 61 | + if (!node.children[char]) return false; |
| 62 | + // ๋ค์ ๋ฌธ์๋ก ์ฌ๊ท ํธ์ถ |
| 63 | + return dfs(node.children[char], i + 1); |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + // ๋ฃจํธ ๋
ธ๋๋ถํฐ ๊ฒ์ ์์ |
| 68 | + return dfs(this.root, 0); |
| 69 | + } |
| 70 | +} |
0 commit comments