Skip to content

Commit ef86fcc

Browse files
committed
design-add-and-search-words-data-structure
1 parent a659557 commit ef86fcc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
var WordDictionary = function () {
2+
this.root = {};
3+
};
4+
5+
/**
6+
* @param {string} word
7+
* @return {void}
8+
*/
9+
WordDictionary.prototype.addWord = function (word) {
10+
let node = this.root;
11+
for (const char of word) {
12+
if (!node[char]) {
13+
// ํ˜„์žฌ ๋ฌธ์ž์— ํ•ด๋‹นํ•˜๋Š” ๋…ธ๋“œ๊ฐ€ ์—†์œผ๋ฉด ์ƒˆ๋กœ ์ƒ์„ฑ
14+
node[char] = { isEnd: false };
15+
}
16+
node = node[char]; // ๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ด๋™
17+
}
18+
node.isEnd = true; // ๋‹จ์–ด ๋ ํ‘œ์‹œ
19+
};
20+
21+
/**
22+
* @param {string} word
23+
* @return {boolean}
24+
*/
25+
WordDictionary.prototype.search = function (word) {
26+
function dfs(node, index) {
27+
// ๋‹จ์–ด์˜ ๋์— ๋„๋‹ฌํ–ˆ์œผ๋ฉด isEnd ๊ฐ’ ๋ฐ˜ํ™˜
28+
if (index === word.length) return node.isEnd;
29+
30+
const char = word[index];
31+
32+
if (node[char]) {
33+
// ํ˜„์žฌ ๋ฌธ์ž๊ฐ€ ๋…ธ๋“œ์— ์กด์žฌํ•˜๋ฉด ํ•ด๋‹น ๋…ธ๋“œ๋กœ ์ด๋™ํ•˜์—ฌ ๊ณ„์† ๊ฒ€์ƒ‰
34+
return dfs(node[char], index + 1);
35+
}
36+
37+
if (char === ".") {
38+
// "."์ธ ๊ฒฝ์šฐ: ๋ชจ๋“  ๊ฐ€๋Šฅํ•œ ๋ฌธ์ž์— ๋Œ€ํ•ด ๊ฒ€์ƒ‰ ์‹œ๋„
39+
return Object.keys(node)
40+
.filter((key) => key !== "isEnd")
41+
.some((key) => dfs(node[key], index + 1)); // ํ•˜๋‚˜๋ผ๋„ true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด true
42+
}
43+
44+
return false;
45+
}
46+
return dfs(this.root, 0);
47+
};
48+
49+
/**
50+
* Your WordDictionary object will be instantiated and called as such:
51+
* var obj = new WordDictionary()
52+
* obj.addWord(word)
53+
* var param_2 = obj.search(word)
54+
*/

0 commit comments

Comments
ย (0)