Skip to content

Commit 3b760c7

Browse files
committed
implement trie prefix tree
1 parent 47acb9b commit 3b760c7

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class TrieNode:
2+
def __init__(self):
3+
# ๋‹ค์Œ ๋ฌธ์ž๋กœ ์—ฐ๊ฒฐ๋˜๋Š” ์ž์‹ ๋…ธ๋“œ
4+
self.children = {}
5+
6+
# ํ˜„์žฌ ๋…ธ๋“œ์—์„œ ํ•˜๋‚˜์˜ ์™„์„ฑ๋œ ๋‹จ์–ด๊ฐ€ ๋๋‚˜๋Š”์ง€ ํ‘œ์‹œ
7+
self.is_end_of_word = False
8+
9+
10+
class Trie:
11+
def __init__(self):
12+
# ๋ชจ๋“  ๋‹จ์–ด ํƒ์ƒ‰์ด ์‹œ์ž‘๋˜๋Š” ์ตœ์ƒ์œ„ ๋…ธ๋“œ
13+
self.root = TrieNode()
14+
15+
def insert(self, word: str) -> None:
16+
current_node = self.root
17+
18+
# ๋‹จ์–ด์˜ ๊ฐ ๋ฌธ์ž๋ฅผ ๋”ฐ๋ผ๊ฐ€๋ฉฐ ๊ฒฝ๋กœ๋ฅผ ์ƒ์„ฑํ•œ๋‹ค.
19+
for char in word:
20+
if char not in current_node.children:
21+
current_node.children[char] = TrieNode()
22+
23+
current_node = current_node.children[char]
24+
25+
# ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ์— ๋‹จ์–ด์˜ ๋์ž„์„ ํ‘œ์‹œํ•œ๋‹ค.
26+
current_node.is_end_of_word = True
27+
28+
def search(self, word: str) -> bool:
29+
last_node = self._find_last_node(word)
30+
31+
# ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•˜๊ณ , ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ์—์„œ ๋‹จ์–ด๊ฐ€ ๋๋‚˜์•ผ ํ•œ๋‹ค.
32+
return (
33+
last_node is not None
34+
and last_node.is_end_of_word
35+
)
36+
37+
def startsWith(self, prefix: str) -> bool:
38+
# ์ ‘๋‘์‚ฌ๋Š” ํ•ด๋‹น ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค.
39+
return self._find_last_node(prefix) is not None
40+
41+
def _find_last_node(self, text: str):
42+
current_node = self.root
43+
44+
# ๋ฌธ์ž์—ด์˜ ๊ฐ ๋ฌธ์ž๋ฅผ ๋”ฐ๋ผ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ๊นŒ์ง€ ์ด๋™ํ•œ๋‹ค.
45+
for char in text:
46+
if char not in current_node.children:
47+
return None
48+
49+
current_node = current_node.children[char]
50+
51+
return current_node

0 commit comments

Comments
ย (0)