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