Skip to content

Commit 817595a

Browse files
committed
design-add-and-search-words-data-structure solution
1 parent 2e484d9 commit 817595a

File tree

1 file changed

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

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
const Node = function() {
2+
this.children = {};
3+
this.isEnd = false;
4+
}
5+
6+
var WordDictionary = function() {
7+
this.root = new Node();
8+
};
9+
10+
/**
11+
* @param {string} word
12+
* @return {void}
13+
*/
14+
WordDictionary.prototype.addWord = function(word) {
15+
let currentNode = this.root;
16+
17+
for (let char of word) {
18+
if (!currentNode.children[char]) {
19+
currentNode.children[char] = new Node();
20+
}
21+
currentNode = currentNode.children[char];
22+
}
23+
24+
currentNode.isEnd = true;
25+
};
26+
27+
/**
28+
* @param {string} word
29+
* @return {boolean}
30+
*/
31+
WordDictionary.prototype.search = function(word) {
32+
if (word === undefined) return false;
33+
return this._search(this.root, word, 0);
34+
};
35+
36+
WordDictionary.prototype._search = function(node, word, index) {
37+
if (index === word.length) {
38+
return node.isEnd;
39+
}
40+
41+
const char = word[index];
42+
43+
if (char !== '.') {
44+
const child = node.children[char];
45+
return child ? this._search(child, word, index + 1) : false;
46+
}
47+
48+
for (const key in node.children) {
49+
if (this._search(node.children[key], word, index + 1)) {
50+
return true;
51+
}
52+
}
53+
54+
return false;
55+
};
56+
57+
/**
58+
* Your WordDictionary object will be instantiated and called as such:
59+
* var obj = new WordDictionary()
60+
* obj.addWord(word)
61+
* var param_2 = obj.search(word)
62+
*/
63+
64+
// n: 단어수, m: 단어 길이
65+
// addWord: 시간 복잡도 O(m)
66+
// search: 시간 복잡도 O(m)
67+
// 공간 복잡도 O(n * m)

0 commit comments

Comments
 (0)