Skip to content

Commit 9f452a9

Browse files
committed
solve: design add and search words data structure
1 parent 5fcfcef commit 9f452a9

File tree

1 file changed

+83
-0
lines changed
  • design-add-and-search-words-data-structure

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
function Node() {
2+
// ๋‹จ์–ด์˜ ๋์„ ์˜๋ฏธ + ๋ฌด์Šจ ๋‹จ์–ด์ธ์ง€ ์ €์žฅ
3+
this.value = null;
4+
// ๋‹จ์–ด์˜ ๋‹ค์Œ ๋ฌธ์ž๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ๋…ธ๋“œ๋งต
5+
this.wordGraph = new Map();
6+
}
7+
8+
var WordDictionary = function () {
9+
this.wordGraph = new Map();
10+
};
11+
12+
/**
13+
* TC: O(N)
14+
* SC: O(1)
15+
*/
16+
17+
/**
18+
* @param {string} word
19+
* @return {void}
20+
*/
21+
WordDictionary.prototype.addWord = function (word) {
22+
let pointer = this;
23+
for (const w of word) {
24+
if (!pointer.wordGraph.has(w)) {
25+
pointer.wordGraph.set(w, new Node());
26+
}
27+
pointer = pointer.wordGraph.get(w);
28+
}
29+
pointer.value = word;
30+
};
31+
32+
/**
33+
* TC: O(D^W)
34+
* SC: O(D * W)
35+
*
36+
* W: word.length, D: count of Dictionary.wordGraph keys
37+
*
38+
* ํ’€์ด: Trie ์ž๋ฃŒ๊ตฌ์กฐ + bfsํƒ์ƒ‰
39+
*/
40+
41+
/**
42+
* @param {string} word
43+
* @return {boolean}
44+
*/
45+
WordDictionary.prototype.search = function (word) {
46+
const queue = [{ pointer: this, index: 0 }];
47+
48+
// 1. BFS ํƒ์ƒ‰ ๋ฐฉ๋ฒ• ์ด์šฉ
49+
while (queue.length > 0) {
50+
const { pointer, index } = queue.shift();
51+
52+
// 2. ์ฐพ๊ณ ์žํ•˜๋Š” ๋‹จ์–ด์˜ ๋์— ๋„๋‹ฌํ–ˆ์œผ๋ฉด ํ•ด๋‹น ๋‹จ์–ด๊ฐ€ ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค.
53+
if (index === word.length) {
54+
if (pointer.value !== null) {
55+
return true;
56+
}
57+
continue;
58+
}
59+
60+
if (word[index] === ".") {
61+
// 3. ์ฐพ๊ณ ์žํ•˜๋Š” ๋‹จ์–ด์˜ ๋ฌธ์ž๊ฐ€ '.'์ธ ๊ฒฝ์šฐ, ํ˜„์žฌ graph์—์„œ ์ด์–ด์ง„ ๋ฌธ์ž๋ฅผ ๋ชจ๋‘ ํƒ์ƒ‰(queue์— ์ถ”๊ฐ€)
62+
for (const [key, node] of pointer.wordGraph) {
63+
queue.push({ pointer: node, index: index + 1 });
64+
}
65+
} else if (pointer.wordGraph.has(word[index])) {
66+
// 4. ์ฐพ๊ณ ์žํ•˜๋Š” ๋‹จ์–ด์˜ ๋ฌธ์ž๊ฐ€ graph์— ์žˆ๋Š” ๊ฒฝ์šฐ ํƒ์ƒ‰(queue์— ์ถ”๊ฐ€)
67+
queue.push({
68+
pointer: pointer.wordGraph.get(word[index]),
69+
index: index + 1,
70+
});
71+
}
72+
}
73+
74+
// 5. ๋”์ด์ƒ ํƒ์ƒ‰ํ•  ๊ฒƒ์ด ์—†๋‹ค๋ฉด ํ•ด๋‹น ๋‹จ์–ด ์—†์Œ์œผ๋กœ ํŒ๋‹จ
75+
return false;
76+
};
77+
78+
/**
79+
* Your WordDictionary object will be instantiated and called as such:
80+
* var obj = new WordDictionary()
81+
* obj.addWord(word)
82+
* var param_2 = obj.search(word)
83+
*/

0 commit comments

Comments
ย (0)