Skip to content

Commit d175f65

Browse files
committed
design-add-and-search-words-data-structure
1 parent 43123dc commit d175f65

File tree

1 file changed

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

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
var WordDictionary = function () {
2+
this.trie = {}; // Trie ๋ฃจํŠธ ๋…ธ๋“œ
3+
};
4+
5+
/**
6+
* @param {string} word
7+
* @return {void}
8+
*/
9+
WordDictionary.prototype.addWord = function (word) {
10+
let current = this.trie;
11+
12+
// ๊ฐ ๋ฌธ์ž๋งˆ๋‹ค ๋…ธ๋“œ ์ƒ์„ฑ
13+
for (let i = 0; i < word.length; i++) {
14+
const char = word[i];
15+
if (!current[char]) {
16+
current[char] = {};
17+
}
18+
current = current[char];
19+
}
20+
21+
// ๋‹จ์–ด์˜ ๋ ํ‘œ์‹œ
22+
current.isEnd = true;
23+
};
24+
25+
/**
26+
* @param {string} word
27+
* @return {boolean}
28+
*/
29+
WordDictionary.prototype.search = function (word) {
30+
return dfs(word, 0, this.trie);
31+
};
32+
33+
/**
34+
* @param {string} word - ๊ฒ€์ƒ‰ํ•  ๋‹จ์–ด
35+
* @param {number} index - ํ˜„์žฌ ๊ฒ€์‚ฌ ์ค‘์ธ ๋ฌธ์ž ์ธ๋ฑ์Šค
36+
* @param {object} node - ํ˜„์žฌ Trie ๋…ธ๋“œ
37+
* @return {boolean}
38+
*/
39+
function dfs(word, index, node) {
40+
// ๋‹จ์–ด ๋์— ๋„๋‹ฌํ–ˆ์œผ๋ฉด isEnd ํ™•์ธ
41+
if (index === word.length) {
42+
return !!node.isEnd;
43+
}
44+
45+
const char = word[index];
46+
47+
if (char === '.') {
48+
// '.'์ธ ๊ฒฝ์šฐ: ๋ชจ๋“  ์ž์‹ ๋…ธ๋“œ๋ฅผ ํƒ์ƒ‰
49+
for (let key in node) {
50+
if (key !== 'isEnd') {
51+
// isEnd ์†์„ฑ์€ ์ œ์™ธ
52+
if (dfs(word, index + 1, node[key])) {
53+
return true;
54+
}
55+
}
56+
}
57+
return false;
58+
} else {
59+
// ์ผ๋ฐ˜ ๋ฌธ์ž์ธ ๊ฒฝ์šฐ: ํ•ด๋‹น ๋ฌธ์ž์˜ ๋…ธ๋“œ๋กœ ์ด๋™
60+
if (!node[char]) {
61+
return false;
62+
}
63+
return dfs(word, index + 1, node[char]);
64+
}
65+
}

0 commit comments

Comments
ย (0)