Skip to content

Commit

Permalink
design-add-and-search-words-data-structure solution
Browse files Browse the repository at this point in the history
  • Loading branch information
yeeZinu committed Jan 13, 2025
1 parent ef91479 commit d5347a5
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions design-add-and-search-words-data-structure/yeeZinu.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// node ํ•จ์ˆ˜์„ ์–ธ
function Node() {
this.child = {};
this.end = false;
}

// ์ตœ์ƒ๋‹จ์˜ ๋ฃจํŠธ๋ฅผ ๋…ธ๋“œ๋กœ ์ดˆ๊ธฐํ™”
var WordDictionary = function () {
this.root = new Node();
};

/**
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function (word) {
// ํ˜„์žฌ์œ„์น˜๋ฅผ ์ตœ์ƒ๋‹จ์œผ๋กœ ์ดˆ๊ธฐํ™”
let current = this.root;

// ๋ฌธ์ž๋ฅผ ๋ฐ›๊ณ  ๋‹จ์–ดํ•˜๋‚˜์”ฉ ๋…ธ๋“œ์— ์ €์žฅ
for (const char of word) {
if (!current.child[char]) {
current.child[char] = new Node();
}
current = current.child[char];
}

// ๋ฐ˜๋ณต์ด ๋๋‚ฌ์œผ๋ฉด true;
current.end = true;

};

/**
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function (word) {

// i ๋ฅผ ๋ฐ›์•„ ๋‹จ์–ด ๋งŒํผ ์žฌ๊ท€ํ•˜๋Š” ํ•จ์ˆ˜
const searchHelper = (current, i) => {
// i์™€ ๋‹จ์–ด์˜ ๊ธธ์ด๊ฐ€ ๊ฐ™์œผ๋ฉด ์ข…๋ฃŒ
if (i === word.length) return current.end;

// ๋‹จ์–ด = ์ฐพ์„ ๋ฌธ์ž์˜ i๋ฒˆ์งธ ๋‹จ์–ด
const char = word[i];

// ๋งŒ์•ฝ ๋ฌธ์ž๊ฐ€ . ๋ผ๋ฉด
if (char === '.') {
// ํ•ด๋‹น ํ˜„์žฌ ๊ฒƒ๋“ค์˜ ํ‚ค๋ฅผ ๊ฐ€์ง€๊ณ  ๋ฐ˜๋ณต
for (const char of Object.keys(current.child)) {
const children = current.child[char];
// end๋ฅผ true๋กœ ํ•˜๊ณ  i+1๋กœ ์žฌ๊ท€
if (searchHelper(children, i + 1)) return true;
}
return false;
}
else {
// ํ˜„์žฌ ์ž์‹์— ํ•ด๋‹น ๋ฌธ์ž๊ฐ€ ์—†์œผ๋ฉด false
if (!(char in current.child)) return false;
// ์•„๋‹ˆ๋ฉด ํ•œ๋ฒˆ ๋” ์žฌ๊ท€
return searchHelper(current.child[char], i + 1);
}
}
// ๊ฒฐ๊ณผ ๋ฆฌํ„ด
return searchHelper(this.root, 0);
};

/**
* Your WordDictionary object will be instantiated and called as such:
* var obj = new WordDictionary()
* obj.addWord(word)
* var param_2 = obj.search(word)
*/

0 comments on commit d5347a5

Please sign in to comment.