-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
design-add-and-search-words-data-structure solution
- Loading branch information
Showing
1 changed file
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
*/ |