Skip to content

Commit f415907

Browse files
author
jinbeom
committed
Implement Trie Solution
1 parent 83f14be commit f415907

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

implement-trie-prefix-tree/kayden.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Node:
2+
3+
def __init__(self, ending=False):
4+
self.children = {}
5+
self.ending = ending
6+
7+
# 공간복잡도: O(w*l) w: 단어 수 l: 단어의 평균 길이
8+
class Trie:
9+
10+
def __init__(self):
11+
self.head = Node(ending=True)
12+
13+
# 시간복잡도: O(N)
14+
def insert(self, word: str) -> None:
15+
node = self.head
16+
for ch in word:
17+
if ch not in node.children:
18+
node.children.setdefault(ch, Node())
19+
node = node.children[ch]
20+
node.ending = True
21+
22+
# 시간복잡도: O(N)
23+
def search(self, word: str) -> bool:
24+
node = self.head
25+
for ch in word:
26+
if ch not in node.children:
27+
return False
28+
node = node.children[ch]
29+
30+
return node.ending
31+
32+
# 시간복잡도: O(N)
33+
def startsWith(self, prefix: str) -> bool:
34+
node = self.head
35+
for ch in prefix:
36+
if ch not in node.children:
37+
return False
38+
node = node.children[ch]
39+
40+
return True

0 commit comments

Comments
 (0)