|
| 1 | +var WordDictionary = function () { |
| 2 | + this.trie = {}; // Trie ๋ฃจํธ ๋
ธ๋ |
| 3 | +}; |
| 4 | + |
| 5 | +/** |
| 6 | + * @param {string} word |
| 7 | + * @return {void} |
| 8 | + */ |
| 9 | +WordDictionary.prototype.addWord = function (word) { |
| 10 | + let current = this.trie; |
| 11 | + |
| 12 | + // ๊ฐ ๋ฌธ์๋ง๋ค ๋
ธ๋ ์์ฑ |
| 13 | + for (let i = 0; i < word.length; i++) { |
| 14 | + const char = word[i]; |
| 15 | + if (!current[char]) { |
| 16 | + current[char] = {}; |
| 17 | + } |
| 18 | + current = current[char]; |
| 19 | + } |
| 20 | + |
| 21 | + // ๋จ์ด์ ๋ ํ์ |
| 22 | + current.isEnd = true; |
| 23 | +}; |
| 24 | + |
| 25 | +/** |
| 26 | + * @param {string} word |
| 27 | + * @return {boolean} |
| 28 | + */ |
| 29 | +WordDictionary.prototype.search = function (word) { |
| 30 | + return dfs(word, 0, this.trie); |
| 31 | +}; |
| 32 | + |
| 33 | +/** |
| 34 | + * @param {string} word - ๊ฒ์ํ ๋จ์ด |
| 35 | + * @param {number} index - ํ์ฌ ๊ฒ์ฌ ์ค์ธ ๋ฌธ์ ์ธ๋ฑ์ค |
| 36 | + * @param {object} node - ํ์ฌ Trie ๋
ธ๋ |
| 37 | + * @return {boolean} |
| 38 | + */ |
| 39 | +function dfs(word, index, node) { |
| 40 | + // ๋จ์ด ๋์ ๋๋ฌํ์ผ๋ฉด isEnd ํ์ธ |
| 41 | + if (index === word.length) { |
| 42 | + return !!node.isEnd; |
| 43 | + } |
| 44 | + |
| 45 | + const char = word[index]; |
| 46 | + |
| 47 | + if (char === '.') { |
| 48 | + // '.'์ธ ๊ฒฝ์ฐ: ๋ชจ๋ ์์ ๋
ธ๋๋ฅผ ํ์ |
| 49 | + for (let key in node) { |
| 50 | + if (key !== 'isEnd') { |
| 51 | + // isEnd ์์ฑ์ ์ ์ธ |
| 52 | + if (dfs(word, index + 1, node[key])) { |
| 53 | + return true; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + return false; |
| 58 | + } else { |
| 59 | + // ์ผ๋ฐ ๋ฌธ์์ธ ๊ฒฝ์ฐ: ํด๋น ๋ฌธ์์ ๋
ธ๋๋ก ์ด๋ |
| 60 | + if (!node[char]) { |
| 61 | + return false; |
| 62 | + } |
| 63 | + return dfs(word, index + 1, node[char]); |
| 64 | + } |
| 65 | +} |
0 commit comments