Skip to content

Commit 712a408

Browse files
committed
feat: week6 - design and search words data structure
1 parent 870556d commit 712a408

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'''
2+
์ด๋ฒˆ ๋ฌธ์ œ๋Š” Trie ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ํ™œ์šฉํ•œ ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.
3+
์ด๋ฅผ ํŒŒ์•…ํ•˜์ง€ ๋ชปํ•ด์„œ ์ „์ฒด ํƒ์ƒ‰ํ•˜๋Š” ๊ตฌ์กฐ๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค ๊ฒฐ๊ตญ ๋˜ ๋„์›€์„ ๋ฐ›์•„ ์ดํ•ดํ•˜๋Š” ๊ฒƒ์— ๋ชฉํ‘œ๋ฅผ ๋’€์Šต๋‹ˆ๋‹ค.
4+
'''
5+
class WordDictionary:
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+
return any(dfs(node[k], idx + 1) for k in node if k != "$")
26+
return False
27+
return dfs(self.root, 0)

0 commit comments

Comments
ย (0)