Skip to content

Commit 16044ef

Browse files
committed
feat: Solve design-add-and-search-words-data-structure problem
1 parent 7345f01 commit 16044ef

File tree

1 file changed

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

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class WordDictionary:
2+
"""
3+
μ•Œκ³ λ‹¬λ ˆμ˜ μ˜μƒμ„ 보고 ν–ˆλŠ”λ° 아직 이해가 잘 λ˜μ§€ μ•ŠμŒ.
4+
좔가적인 ν•™μŠ΅ ν•„μš”
5+
"""
6+
def __init__(self):
7+
self.root = {"$": True}
8+
9+
def addWord(self, word: str) -> None:
10+
node = self.root
11+
for ch in word:
12+
if ch not in node:
13+
node[ch] = {"$": False}
14+
node = node[ch]
15+
node["$"] = True
16+
17+
def search(self, word: str) -> bool:
18+
def dfs(node, idx):
19+
if idx == len(word):
20+
return node["$"]
21+
ch = word[idx]
22+
if ch in node:
23+
return dfs(node[ch], idx + 1)
24+
if ch == ".":
25+
if any(dfs(node[k], idx + 1) for k in node if k != "$"):
26+
return True
27+
return False
28+
29+
return dfs(self.root, 0)
30+
31+
32+
# Your WordDictionary object will be instantiated and called as such:
33+
# obj = WordDictionary()
34+
# obj.addWord(word)
35+
# param_2 = obj.search(word)

0 commit comments

Comments
Β (0)