Skip to content

Commit f18bb1c

Browse files
committed
feat: design-add-and-search-words-data-structure
1 parent d807266 commit f18bb1c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# 문제유형 : Trie
2+
class WordDictionary:
3+
def __init__(self):
4+
self.trie = {}
5+
6+
# 시간 복잡도 : O(N)
7+
# 공간 복잡도 : O(N)
8+
def addWord(self, word: str) -> None:
9+
node = self.trie
10+
for char in word:
11+
if char not in node:
12+
node[char] = {}
13+
node = node[char]
14+
node['$'] = True
15+
16+
# 시간 복잡도 : O(m^N) (m : 철자의 종류, N : 문자열의 길이)
17+
def search(self, word: str) -> bool:
18+
return self.dfs(0, self.trie, word)
19+
20+
def dfs(self, i, node, word):
21+
if i == len(word):
22+
return '$' in node
23+
if word[i] == '.':
24+
for child in node.values():
25+
if isinstance(child, dict) and self.dfs(i + 1, child, word):
26+
return True
27+
if word[i] in node:
28+
return self.dfs(i + 1, node[word[i]], word)
29+
return False
30+

0 commit comments

Comments
 (0)