Skip to content

Commit d8e7390

Browse files
committed
design-add-and-search-words-data-structure solution
1 parent bb9a7dd commit d8e7390

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Node:
2+
def __init__(self, char=None):
3+
self.is_end = False
4+
self.children = {}
5+
6+
class WordDictionary:
7+
"""
8+
트라이를 활용
9+
기본 문제와 다른 점은 search 할 때 "." 이 포함되어있는 것
10+
11+
따라서 . 이라면 해당 노드의 모든 자식을 모두 조회해야됨
12+
13+
addWord
14+
w = len(word)
15+
Tc : O(w)
16+
Sc : O(w)
17+
18+
search
19+
최악의 경우 case : xa, xb, xc, xd, .... xz 로 x의 다음 글자가 a~z일 때
20+
search("x.") 라면 26개 모두를 찾아봐야됨
21+
Tc : O(26^w)
22+
Sc : O(w) (글자 길이만큼 재귀를 호출하기에)
23+
24+
"""
25+
def __init__(self):
26+
self.root = Node()
27+
28+
def addWord(self, word: str) -> None:
29+
now = self.root
30+
31+
for ch in word:
32+
if ch not in now.children:
33+
now.children[ch] = Node(ch)
34+
now = now.children[ch]
35+
now.is_end = True
36+
37+
def search(self, word: str) -> bool:
38+
def _recur_search(node, index):
39+
if index == len(word):
40+
return node.is_end
41+
42+
if word[index] == ".":
43+
for ch in node.children:
44+
if _recur_search(node.children[ch], index+1):
45+
return True
46+
47+
if word[index] in node.children:
48+
return _recur_search(node.children[word[index]], index+1)
49+
return False
50+
51+
return _recur_search(self.root, 0)
52+
53+
54+
55+
56+
# Your WordDictionary object will be instantiated and called as such:
57+
# obj = WordDictionary()
58+
# obj.addWord(word)
59+
# param_2 = obj.search(word)
60+

0 commit comments

Comments
 (0)