Skip to content

Commit b4ad510

Browse files
committed
#257 solution
1 parent 87b134c commit b4ad510

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
풀이 :
3+
Trie를 활용해서 단어를 저장한다
4+
글자마다 이어지는 다음 글자에 대한 children[26](알파벳 소문자 개수 26개)를 가지고 현재 글자에서 끝나는지 여부(isEnd)를 가진다
5+
6+
addWord는 한글자씩 node에 없으면 추가하고 다음 글자의 노드로 이동하며
7+
word에 대한 반복을 마친 뒤 마지막 node의 isEnd를 1로 바꿈
8+
9+
search는 한글자씩 다음 노드로 이동하며 word의 끝에 다다랐을 떄 isEnd가 1인지 return
10+
dfs를 활용하여 '.'이 나올 경우 알파벳 26개 모두에 대해 다음 글자부터 시작하는 dfs를 호출
11+
12+
word의 길이 : W
13+
14+
TC :
15+
addWord : O(W)
16+
word 길이에 비례하여 반복문
17+
18+
search : O(26^W)
19+
최악의 경우 word길이 만큼 '.'이 있으면 하나하나 마다 26번의 재귀호출이 있다
20+
21+
SC :
22+
addWord : O(W)
23+
TrieNode 개수는 word길이에 비례
24+
25+
search : O(W)
26+
재귀 호출스택은 word 길이에 비례
27+
*/
28+
29+
class WordDictionary {
30+
private:
31+
struct TrieNode {
32+
int isEnd = 0;
33+
TrieNode* children[26] = {};
34+
};
35+
TrieNode* root;
36+
37+
public:
38+
WordDictionary() {
39+
this->root = new TrieNode();
40+
}
41+
42+
void addWord(string word) {
43+
TrieNode* node = root;
44+
for (auto& c : word)
45+
{
46+
int idx = c - 'a';
47+
if (!node->children[idx])
48+
node->children[idx] = new TrieNode();
49+
node = node->children[idx];
50+
}
51+
node->isEnd = 1;
52+
}
53+
54+
bool search(string word) {
55+
return dfs(word, this->root);
56+
}
57+
58+
bool dfs(string word, TrieNode* node) {
59+
if (word.empty())
60+
return node->isEnd;
61+
62+
for (int i = 0; i < word.size(); i++)
63+
{
64+
if (word[i] == '.')
65+
{
66+
for (int j=0; j < 26; j++)
67+
{
68+
if (node->children[j] && this->dfs(word.substr(i + 1), node->children[j]))
69+
return true;
70+
}
71+
return false;
72+
}
73+
int idx = word[i] - 'a';
74+
if (!node->children[idx])
75+
return false;
76+
node = node->children[idx];
77+
}
78+
return node->isEnd;
79+
}
80+
};
81+
82+
/**
83+
* Your WordDictionary object will be instantiated and called as such:
84+
* WordDictionary* obj = new WordDictionary();
85+
* obj->addWord(word);
86+
* bool param_2 = obj->search(word);
87+
*/

0 commit comments

Comments
 (0)