Skip to content

Commit 6ae8b94

Browse files
committed
design-add-and-search-words-data-structure
1 parent cf36d77 commit 6ae8b94

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# prefix ๊ธฐ๋ฐ˜์œผ๋กœ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ๋Š” ํŠธ๋ผ์ด๋…ธ๋“œ ์ž๋ฃŒ๊ตฌ์กฐ ํ™œ์šฉ
2+
class TrieNode:
3+
def __init__(self):
4+
self.children = {}
5+
self.is_ending = False
6+
7+
class WordDictionary:
8+
9+
def __init__(self):
10+
self.root = TrieNode()
11+
12+
def addWord(self, word: str) -> None:
13+
current_node = self.root
14+
for char in word:
15+
if char not in current_node.children:
16+
current_node.children[char] = TrieNode()
17+
current_node = current_node.children[char]
18+
current_node.is_ending = True
19+
20+
def search(self, word):
21+
def dfs(node, index):
22+
# ๋‹จ์–ด์ž๋ฆฌ์ˆ˜๋งŒํผ ์™”๊ณ , ๋๋‹จ์–ด์ธ๊ฒฝ์šฐ ์ฐพ๊ธฐ ์„ฑ๊ณต
23+
if index == len(word):
24+
return node.is_ending
25+
# ์™€์ผ๋“œ์นด๋“œ์ธ ๊ฒฝ์šฐ ์ž์‹๋“ค ์ „๋ถ€ ํƒ์ƒ‰
26+
if word[index] == ".":
27+
for child in node.children.values():
28+
if dfs(child, index+1):
29+
return True
30+
# ์ผ๋ฐ˜์ ์ธ ๊ฒฝ์šฐ ๋‹ค์Œ ์ž์‹ ํƒ์ƒ‰
31+
if word[index] in node.children:
32+
return dfs(node.children[word[index]], index+1)
33+
return False
34+
return dfs(self.root, 0)
35+
36+
37+
# Your WordDictionary object will be instantiated and called as such:
38+
# obj = WordDictionary()
39+
# obj.addWord(word)
40+
# param_2 = obj.search(word)

0 commit comments

Comments
ย (0)