Skip to content

Commit f94110e

Browse files
authored
[ PS ] : Design Add And Search Words Data Structure
1 parent 52d8c2a commit f94110e

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class TrieNode {
2+
constructor(value) {
3+
this.value = value;
4+
this.children = {};
5+
this.end = false;
6+
}
7+
}
8+
9+
class WordDictionary {
10+
constructor() {
11+
this.root = new TrieNode(null);
12+
}
13+
14+
/**
15+
* 시간복잡도: O(w) (w: word.length)
16+
* 공간복잡도: O(w)
17+
* @param {string} word
18+
* @return {void}
19+
*/
20+
addWord(word) {
21+
let current = this.root;
22+
23+
for (const char of word) {
24+
if (!current.children[char]) {
25+
const child = new TrieNode(char);
26+
current.children[char] = child;
27+
}
28+
current = current.children[char];
29+
}
30+
31+
current.end = true;
32+
};
33+
34+
/**
35+
* 시간복잡도: O(k * w) (k: children의 길이로 최대 26, w: word.length)
36+
* 공간복잡도: O(w)
37+
* @param {string} word
38+
* @return {boolean}
39+
*/
40+
search(word) {
41+
return this.#search(this.root, word, 0);
42+
};
43+
44+
#search(node, word, idx) {
45+
if (!node) return false;
46+
if (idx >= word.length) return node.end;
47+
48+
if (word[idx] === '.') {
49+
for (const current of Object.values(node.children)) {
50+
if (this.#search(current, word, idx + 1)) {
51+
return true;
52+
}
53+
}
54+
return false;
55+
} else {
56+
return this.#search(node.children[word[idx]], word, idx + 1);
57+
}
58+
}
59+
};

0 commit comments

Comments
 (0)