Skip to content

Commit 0060e06

Browse files
committed
design-add-and-search-words-data-structure solution
1 parent 77917b1 commit 0060e06

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class TrieNode {
2+
constructor() {
3+
this.children = {}; // ๋ฌธ์ž -> TrieNode ๋งคํ•‘
4+
this.isEnd = false; // ๋‹จ์–ด์˜ ๋ ํ‘œ์‹œ
5+
}
6+
}
7+
8+
class WordDictionary {
9+
constructor() {
10+
this.root = new TrieNode();
11+
}
12+
13+
/**
14+
* ๋‹จ์–ด๋ฅผ ํŠธ๋ผ์ด์— ์ถ”๊ฐ€
15+
* Time Complexity: O(L) // L = word.length
16+
* Space Complexity: O(L) // ์ƒˆ๋กœ์šด ๋…ธ๋“œ ์ตœ๋Œ€ L๊ฐœ ์ถ”๊ฐ€ ๊ฐ€๋Šฅ
17+
*/
18+
addWord(word) {
19+
let node = this.root;
20+
for (const char of word) {
21+
if (!node.children[char]) {
22+
node.children[char] = new TrieNode();
23+
}
24+
node = node.children[char];
25+
}
26+
node.isEnd = true;
27+
}
28+
29+
/**
30+
* ๋‹จ์–ด ๋˜๋Š” ํŒจํ„ด ๊ฒ€์ƒ‰
31+
* Time Complexity: O(26^D * L) // D = '.' ๊ฐœ์ˆ˜ (์ตœ๋Œ€ 2), L = word.length
32+
* Space Complexity: O(L) // DFS ์žฌ๊ท€ ํ˜ธ์ถœ ์Šคํƒ ๊นŠ์ด
33+
*/
34+
search(word) {
35+
const dfs = (index, node) => {
36+
for (let i = index; i < word.length; i++) {
37+
const char = word[i];
38+
if (char === '.') {
39+
for (const child of Object.values(node.children)) {
40+
if (dfs(i + 1, child)) return true;
41+
}
42+
return false;
43+
} else {
44+
if (!node.children[char]) return false;
45+
node = node.children[char];
46+
}
47+
}
48+
return node.isEnd;
49+
};
50+
51+
return dfs(0, this.root);
52+
}
53+
}

0 commit comments

Comments
ย (0)