Skip to content

Commit e75b852

Browse files
committed
design-add-and-search-words-data-structure solution
1 parent b942db6 commit e75b852

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class TrieNode:
2+
def __init__(self):
3+
self.children = {}
4+
self.is_end = False
5+
6+
class WordDictionary:
7+
''' 너무 어려워숴 풀이 봤어요..ㅠㅠ'''
8+
9+
def __init__(self):
10+
self.root = TrieNode()
11+
12+
def addWord(self, word: str) -> None:
13+
node = self.root
14+
15+
for ch in word:
16+
#node 에 존재하지 않으면 TrieNode 생성
17+
if ch not in node.children:
18+
node.children[ch] = TrieNode()
19+
#node 에 children 저장
20+
node = node.children[ch]
21+
node.is_end = True
22+
23+
def dfs(self, node, word, i):
24+
if i == len(word):
25+
return node.is_end
26+
27+
#일반 문자일 경우
28+
ch = word[i]
29+
if ch != '.':
30+
if ch not in node.children:
31+
return False
32+
return self.dfs(node.children[ch], word, i + 1)
33+
#.이 포함된 경우 -> 모든 경우 탐색
34+
for child in node.children.values():
35+
if self.dfs(child, word, i + 1):
36+
return True
37+
return False
38+
39+
def search(self, word: str) -> bool:
40+
return self.dfs(self.root, word, 0)
41+
42+
43+
44+
# Your WordDictionary object will be instantiated and called as such:
45+
# obj = WordDictionary()
46+
# obj.addWord(word)
47+
# param_2 = obj.search(word)

0 commit comments

Comments
 (0)