Skip to content

Commit ef0e033

Browse files
committed
[7th batch] week 5 - implement trie prefix tree
1 parent 38fb272 commit ef0e033

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# 7๊ธฐ ํ’€์ด
2+
# Trie ์ „์ฒด ๊ณต๊ฐ„ ๋ณต์žก๋„: ๊ณต๊ฐ„: O(n * m)
3+
# - n์€ ๋‹จ์–ด ์ˆ˜, m์€ ํ‰๊ท  ๋‹จ์–ด ๊ธธ์ด
4+
# ๊ฐ ๋ฉ”์„œ๋“œ ๋งˆ๋‹ค ์‹œ๊ฐ„ ๋ณต์žก๋„์™€ ๊ณต๊ฐ„ ๋ณต์žก๋„ ์ž‘์„ฑ
5+
class Node:
6+
def __init__(self, val=None):
7+
self.children = {} # ์ž์‹ ๋…ธ๋“œ๋ฅผ ๋‹ด์„ dictionary
8+
self.is_end = False # ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๋์œผ๋กœ ํ•˜๋Š” ๋‹จ์–ด๊ฐ€ ์ €์žฅ๋˜์—ˆ๋Š”์ง€์— ๋Œ€ํ•œ flag
9+
10+
11+
class Trie:
12+
def __init__(self):
13+
self.root = Node()
14+
15+
def insert(self, word: str) -> None:
16+
# ์‹œ๊ฐ„: O(m) โ€” m์€ word์˜ ๊ธธ์ด, ๋ฌธ์ž ํ•˜๋‚˜์”ฉ ์ˆœํšŒ
17+
# ๊ณต๊ฐ„: O(m) โ€” ์ตœ์•…์˜ ๊ฒฝ์šฐ m๊ฐœ์˜ ์ƒˆ ๋…ธ๋“œ ์ƒ์„ฑ (์•„๋ฌด๊ฒƒ๋„ ๊ณต์œ  ์•ˆํ•  ๋•Œ)
18+
node = self.root
19+
for s in word:
20+
if s not in node.children: # ์•„์ง ์ €์žฅ์ด ๋˜์ง€ ์•Š์€ ๋ฌธ์ž๋ผ๋ฉด children์— ๋…ธ๋“œ๋กœ์จ ์ €์žฅํ•ด๋‘”๋‹ค.
21+
node.children[s] = Node(s)
22+
node = node.children[s] # ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ children node๋กœ ์ง€์ •ํ•˜์—ฌ ํ›„์†๊นŒ์ง€ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•จ
23+
node.is_end = True # ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•œ ํ›„์—๋Š” ๋‹จ์–ด์˜ ๋์„ ์•Œ๋ฆฌ๋„๋ก is_end๋ฅผ True๋กœ ๋ณ€๊ฒฝ
24+
25+
def search(self, word: str) -> bool:
26+
# ์‹œ๊ฐ„: O(m) โ€” m์€ word/prefix์˜ ๊ธธ์ด๋งŒํผ ์ˆœํšŒ
27+
# ๊ณต๊ฐ„: O(1) โ€” ์ƒˆ ๋…ธ๋“œ ์ƒ์„ฑ ์—†์ด ํฌ์ธํ„ฐ๋งŒ ์ด๋™
28+
node = self.root
29+
for s in word:
30+
if s not in node.children: # ์ฐพ์œผ๋ ค๋Š” ๋‹จ์–ด์˜ ๋ฌธ์ž๊ฐ€ ์ €์žฅ๋˜์–ด ์žˆ์ง€ ์•Š์œผ๋ฉด search ์‹คํŒจ์ด๋ฏ€๋กœ False ๋ฐ˜ํ™˜
31+
return False
32+
node = node.children[s]
33+
34+
return node.is_end # ๋๊นŒ์ง€ ๋Œ์•„๋ณด๊ณ  ํ•ด๋‹น ๋‹จ์–ด์˜ ๋์ด ์ €์žฅ๋˜์–ด ์žˆ๋Š”์ง€ ์•„๋‹Œ์ง€๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฏ€๋กœ์จ search์˜ ์„ฑํŒจ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Œ
35+
36+
def startsWith(self, prefix: str) -> bool:
37+
# start with์˜ ๊ฒฝ์šฐ์—๋Š”, search์™€ ๊ฑฐ์˜ ๋กœ์ง์ด ๋™์ผํ•˜๋‚˜, is_end์˜ ์—ฌ๋ถ€๋ฅผ ๋ณผ ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ ๋ชจ๋“  ๋ฌธ์ž์— ๋Œ€ํ•œ search๊ฐ€ ๋๋‚˜๋ฉด ๋ฌด์กฐ๊ฑด True ๋ฐ˜ํ™˜
38+
node = self.root
39+
for s in prefix:
40+
if s not in node.children:
41+
return False
42+
node = node.children[s]
43+
44+
return True
45+

0 commit comments

Comments
ย (0)