Skip to content

Commit e08cf3a

Browse files
committed
design-add-and-search-words-data-structure solution
1 parent ebe936c commit e08cf3a

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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

Comments
ย (0)