Skip to content

Commit 684763d

Browse files
committed
design-add-and-search-words-data-structure solution
1 parent f59a4d7 commit 684763d

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
"""
2+
TrieNode: ν•œ κΈ€μžλ₯Ό λ‹΄λŠ” λ…Έλ“œ
3+
- children: μžμ‹λ…Έλ“œλ“€ μ €μž₯ν•˜λŠ” λ”•μ…”λ„ˆλ¦¬
4+
- end: ν•΄λ‹Ή λ…Έλ“œμ—μ„œ 단어가 λλ‚˜λŠ”μ§€ μ—¬λΆ€
5+
"""
6+
class TrieNode:
7+
# Trie λ…Έλ“œ μ΄ˆκΈ°ν™”
8+
def __init__(self):
9+
self.children = {} # μžμ‹ λ…Έλ“œ μ €μž₯
10+
self.end = False # λ‹¨μ–΄μ˜ 끝인지 ν‘œμ‹œ
11+
12+
"""
13+
Trie(트라이)ꡬ쑰, DFS, μž¬κ·€
14+
- addWord : 단어λ₯Ό Trie에 μ‚½μž…
15+
- search : 단어가 Trie에 μ‘΄μž¬ν•˜λŠ”μ§€ 검색
16+
"""
17+
class WordDictionary:
18+
19+
# Trie 자료ꡬ쑰 μ΄ˆκΈ°ν™”(루트 λ…Έλ“œ 생성)
20+
def __init__(self):
21+
# Trie의 μ‹œμž‘(빈 루트 λ…Έλ“œ 생성)
22+
self.root = TrieNode()
23+
24+
def addWord(self, word: str) -> None:
25+
node = self.root # 단어 μ‚½μž…μ˜ μ‹œμž‘ μœ„μΉ˜ = 루트 λ…Έλ“œ
26+
27+
# λ‹¨μ–΄μ˜ κΈ€μž ν•˜λ‚˜ν•˜λ‚˜λ₯Ό Trie에 μ‚½μž…
28+
for i in word:
29+
# κΈ€μžκ°€ μžμ‹ λ…Έλ“œμ— μ—†μœΌλ©΄ μƒˆλ‘œμš΄ λ…Έλ“œ μƒμ„±ν•΄μ„œ λ»—μ–΄κ°€κΈ°
30+
if i not in node.children:
31+
node.children[i] = TrieNode()
32+
33+
node = node.children[i] # λ‹€μŒ κΈ€μž(λ…Έλ“œ)둜 이동
34+
35+
node.end = True # 단어 μ‚½μž… μ™„λ£Œ, ν˜„μž¬ λ…Έλ“œμ—μ„œ λ‹¨μ–΄μ˜ 끝 ν‘œμ‹œ(True)
36+
37+
38+
def search(self, word: str) -> bool:
39+
40+
def dfs(node,i):
41+
# 단어λ₯Ό λ‹€ 돌고 λ§ˆμ§€λ§‰ λ…Έλ“œκ°€ λ‹¨μ–΄μ˜ 끝이면 node.endλŠ” True
42+
if i == len(word):
43+
return node.end
44+
45+
if word[i] == ".":
46+
# "." 일 경우 λͺ¨λ“  μžμ‹ λ…Έλ“œ λŒ€μƒμœΌλ‘œ μž¬κ·€ 탐색
47+
for j in node.children.values():
48+
if dfs(j, i+1):
49+
return True
50+
else:
51+
# "."이 μ•„λ‹Œ 경우 μžμ‹λ…Έλ“œμ— μžˆλŠ”μ§€ 확인.
52+
# 있으면 λ‹€μŒ κΈ€μž 탐색, μ—†μœΌλ©΄ False 리턴
53+
if word[i] in node.children:
54+
return dfs(node.children[word[i]], i+1)
55+
else:
56+
return False
57+
58+
# μΌμΉ˜ν•˜λŠ” 단어가 μ—†λŠ” κ²½μš°μ— λŒ€λΉ„ν•œ μ˜ˆμ™Έ 처리
59+
return False
60+
61+
# DFSμ‹œμž‘(루트 λ…Έλ“œλΆ€ν„° 탐색)
62+
return dfs(self.root, 0)
63+
64+
# Your WordDictionary object will be instantiated and called as such:
65+
# obj = WordDictionary()
66+
# obj.addWord(word)
67+
# param_2 = obj.search(word)

0 commit comments

Comments
Β (0)