Skip to content

Commit 36259bf

Browse files
author
jinbeom
committed
Design Add and Search Words Data Structure Solution
1 parent 35fe589 commit 36259bf

File tree

1 file changed

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

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Node:
2+
def __init__(self, ending=False):
3+
self.ending = ending
4+
self.children = {}
5+
6+
7+
class WordDictionary:
8+
9+
def __init__(self):
10+
self.head = Node(True)
11+
12+
# ์‹œ๊ฐ„๋ณต์žก๋„: O(W)
13+
def addWord(self, word: str) -> None:
14+
node = self.head
15+
16+
for ch in word:
17+
if ch not in node.children:
18+
node.children.setdefault(ch, Node())
19+
node = node.children[ch]
20+
21+
node.ending = True
22+
23+
# ์‹œ๊ฐ„๋ณต์žก๋„: O(W*N) W: word ๊ธธ์ด N: ์ž์‹ ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜
24+
def search(self, word: str) -> bool:
25+
def dfs(idx, node):
26+
if idx == len(word):
27+
return node.ending
28+
29+
if word[idx] == '.':
30+
for n in node.children.values():
31+
if dfs(idx + 1, n):
32+
return True
33+
elif word[idx] in node.children:
34+
return dfs(idx + 1, node.children[word[idx]])
35+
else:
36+
return False
37+
38+
return dfs(0, self.head)

0 commit comments

Comments
ย (0)