File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments