Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 8244215

Browse files
committedMay 5, 2025·
solve(w06): 211. Design Add and Search Words Data Structure
1 parent 9705306 commit 8244215

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
 
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# https://leetcode.com/problems/design-add-and-search-words-data-structure/
2+
3+
from collections import defaultdict, deque
4+
5+
class TrieNode:
6+
def __init__(self):
7+
self.is_word = False
8+
self.children = defaultdict(TrieNode)
9+
10+
class WordDictionary:
11+
def __init__(self):
12+
self.root = TrieNode()
13+
14+
def addWord(self, word: str) -> None:
15+
curr = self.root
16+
17+
for w in word:
18+
curr = curr.children[w]
19+
20+
curr.is_word = True
21+
22+
def search(self, word: str) -> bool:
23+
"""
24+
BFS 혹은 DFS를 사용할 수 있다. 핵심은
25+
- "."을 마주치면 모든 children을 전부 타고 내려간다.
26+
- "."이 아닌 문자를 확인해야 한다면 해당 문자가 children에 있는지 확인 후 타고 내려간다.
27+
는 것이다.
28+
"""
29+
# return self._bfs(word)
30+
return self._dfs(self.root, word, 0)
31+
32+
def _dfs(self, curr, word, idx):
33+
# base condition
34+
if idx == len(word):
35+
return curr.is_word
36+
37+
# recur
38+
# (1) "."을 마주치면 모든 children에 대해 타고 내려간다.
39+
if word[idx] == ".":
40+
for child in curr.children.values():
41+
if self._dfs(child, word, idx + 1):
42+
return True
43+
44+
# (2) 현재 idx의 문자가 children에 있는지 확인 후에 타고 내려간다.
45+
if (w := word[idx]) in curr.children:
46+
return self._dfs(curr.children[w], word, idx + 1)
47+
48+
# (3) 그 외의 경우, False를 반환한다.
49+
return False
50+
51+
def _bfs(self, word):
52+
q = deque([(self.root, 0)]) # (node, idx)
53+
54+
while q:
55+
curr, idx = q.popleft()
56+
57+
# base condition
58+
if idx == len(word):
59+
if curr.is_word:
60+
return True
61+
62+
# iter
63+
# (1) "."을 마주치면 모든 children에 대해 타고 내려간다.
64+
elif word[idx] == ".":
65+
for child in curr.children.values():
66+
q.append((child, idx + 1))
67+
68+
# (2) 현재 idx의 문자가 children에 있는지 확인 후에 타고 내려간다.
69+
else:
70+
if (w := word[idx]) in curr.children:
71+
q.append((curr.children[w], idx + 1))
72+
73+
# (3) 그 외의 경우, False를 반환한다.
74+
return False
75+
76+
# Your WordDictionary object will be instantiated and called as such:
77+
# obj = WordDictionary()
78+
# obj.addWord(word)
79+
# param_2 = obj.search(word)

0 commit comments

Comments
 (0)
Please sign in to comment.