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
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)