Skip to content

Commit 70b935d

Browse files
committed
implement-trie-prefix-tree solution
1 parent 402f18f commit 70b935d

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(트라): Tree기반의 자료ꡬ쑰(Treeμžλ£Œκ΅¬μ‘°μ€‘ν•˜λ‚˜), λ¬Έμžμ—΄ 검색을 μœ„ν•œ νŠΉμˆ˜ν•œ Tree 자료ꡬ쑰
14+
- insert: μ£Όμ–΄μ§„ word μ‚½μž…
15+
- search: μ£Όμ–΄μ§„ wordκ°€ Trie에 μžˆλŠ”μ§€ 검색
16+
- startwith: μ£Όμ–΄μ§„ prefix둜 μ‹œμž‘ν•˜λŠ” 단어가 μžˆλŠ”μ§€ 확인
17+
"""
18+
class Trie:
19+
# Trie 자료ꡬ쑰 μ΄ˆκΈ°ν™”(루트 λ…Έλ“œ 생성)
20+
def __init__(self):
21+
# Trie의 μ‹œμž‘(빈 루트 λ…Έλ“œ 생성)
22+
self.root = TrieNode()
23+
24+
def insert(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+
def search(self, word: str) -> bool:
38+
node = self.root
39+
40+
for i in word:
41+
# κΈ€μžκ°€ μžμ‹λ…Έλ“œμ— μ‘΄μž¬ν•˜μ§€ μ•ŠμœΌλ©΄ False 리턴
42+
if i not in node.children:
43+
return False
44+
45+
node = node.children[i] # λ‹€μŒ κΈ€μž(λ…Έλ“œ)둜 이동
46+
47+
# 단어λ₯Ό λ‹€ 돌고 λ§ˆμ§€λ§‰ λ…Έλ“œκ°€ λ‹¨μ–΄μ˜ 끝이면 node.endλŠ” True
48+
return node.end
49+
50+
def startsWith(self, prefix: str) -> bool:
51+
node = self.root
52+
53+
for i in prefix:
54+
# κΈ€μžκ°€ μžμ‹λ…Έλ“œμ— μ‘΄μž¬ν•˜μ§€ μ•ŠμœΌλ©΄ False 리턴
55+
if i not in node.children:
56+
return False
57+
58+
node = node.children[i] # λ‹€μŒ κΈ€μž(λ…Έλ“œ)둜 이동
59+
60+
return True
61+
62+
63+
# Your Trie object will be instantiated and called as such:
64+
# obj = Trie()
65+
# obj.insert(word)
66+
# param_2 = obj.search(word)
67+
# param_3 = obj.startsWith(prefix)

0 commit comments

Comments
Β (0)