Skip to content

Commit 3e2c6d9

Browse files
committed
implement trie solution
1 parent fd2cd7a commit 3e2c6d9

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Recursive vs Iterative
3+
4+
재귀 방식의 경우, 만약 문자열의 길이가 굉장히 길다면 그만큼의 콜이 일어나고 이는 성능적으로 느려질 수 있음.
5+
두 가지 모두 시간 복잡도 면에서는 O(m) 임 (m = len(string))
6+
7+
Node 클래스를 따로 두어 처리하면 가독성 높게 처리할 수 있다.
8+
"""
9+
10+
class Node:
11+
def __init__(self, key=None):
12+
self.key = key
13+
self.children = {}
14+
self.is_end = False
15+
16+
class Trie:
17+
def __init__(self):
18+
self.head = Node()
19+
20+
def insert(self, word: str) -> None:
21+
curr = self.head
22+
23+
for ch in word:
24+
if ch not in curr.children:
25+
curr.children[ch] = Node(ch)
26+
curr = curr.children[ch]
27+
curr.is_end = True
28+
29+
def search(self, word: str) -> bool:
30+
curr = self.head
31+
32+
for ch in word:
33+
if ch not in curr.children:
34+
return False
35+
curr = curr.children[ch]
36+
37+
return curr.is_end
38+
39+
def startsWith(self, prefix: str) -> bool:
40+
curr = self.head
41+
42+
for ch in prefix:
43+
if ch not in curr.children:
44+
return False
45+
curr = curr.children[ch]
46+
return True
47+

0 commit comments

Comments
 (0)