Skip to content

Commit 02e60bb

Browse files
committed
Solution: Design Add and Search Words Data Structure
1 parent b0a4234 commit 02e60bb

File tree

1 file changed

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

1 file changed

+89
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/**
2+
* 풀이
3+
* - Trie 구조를 활용하여 풀이할 수 있습니다
4+
* - wildcard인 '.'에 대한 처리가 필요합니다
5+
*
6+
* Big O
7+
* - N: 주어지는 문자열 word의 길이
8+
* - M: 현재 WordDictionary에 저장되어 있는 TrieNode의 수
9+
*
10+
* - void addWord(string word)
11+
* - Time complexity: O(N)
12+
* - Space complexity: O(N)
13+
* - 최악의 경우 word의 모든 문자에 대해 새로운 TrieNode를 추가해야 합니다
14+
*
15+
* - bool search(string word)
16+
* - bool _search(string word, int idx, TrieNode* node)
17+
* - Time complexity: best O(N), worst O(M) < O(26^N)
18+
* - wildcard 사용 및 기존에 저장된 word의 상태에 따라 달라집니다
19+
* - Space complexity: O(N)
20+
* - _search가 재귀적으로 호출되므로 재귀 호출 스택의 깊이만큼 추가적인 공간이 사용됩니다
21+
* - 재귀 호출 스택의 깊이는 현재 찾는 word의 길이에 선형적으로 비례합니다
22+
*/
23+
24+
class TrieNode {
25+
public:
26+
array<TrieNode*, 27> links;
27+
bool word;
28+
29+
TrieNode(): word(false) {
30+
links.fill(nullptr);
31+
}
32+
};
33+
34+
class WordDictionary {
35+
public:
36+
WordDictionary(): root(new TrieNode()) {}
37+
38+
void addWord(string word) {
39+
TrieNode* current = root;
40+
41+
for (char c : word) {
42+
if (current->links[c - 'a'] == nullptr) {
43+
current->links[c - 'a'] = new TrieNode();
44+
}
45+
current = current->links[c - 'a'];
46+
}
47+
48+
current->word = true;
49+
}
50+
51+
bool search(string word) {
52+
return _search(word, 0, root);
53+
}
54+
55+
private:
56+
TrieNode* root;
57+
58+
bool _search(string word, int idx, TrieNode* node) {
59+
if (word.size() == idx) return node->word;
60+
61+
char c = word[idx];
62+
63+
if (c != '.') {
64+
if (node->links[c - 'a'] == nullptr) return false;
65+
66+
TrieNode* next_node = node->links[c - 'a'];
67+
int next_idx = idx + 1;
68+
69+
return _search(word, next_idx, next_node);
70+
} else {
71+
for (TrieNode* link : node->links) {
72+
if (link != nullptr) {
73+
TrieNode* next_node = link;
74+
int next_idx = idx + 1;
75+
76+
if (_search(word, next_idx, next_node)) return true;
77+
}
78+
}
79+
return false;
80+
}
81+
}
82+
};
83+
84+
/**
85+
* Your WordDictionary object will be instantiated and called as such:
86+
* WordDictionary* obj = new WordDictionary();
87+
* obj->addWord(word);
88+
* bool param_2 = obj->search(word);
89+
*/

0 commit comments

Comments
 (0)