File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TrieNode :
2
+ def __init__ (self ):
3
+ self .isEnd = False
4
+ self .links = {}
5
+
6
+
7
+ class Trie :
8
+
9
+ def __init__ (self ):
10
+ self ._root = TrieNode ()
11
+
12
+ def _recurAdd (self , node : TrieNode , word : str ) -> None :
13
+ if not word :
14
+ node .isEnd = True
15
+ return
16
+
17
+ ch = word [0 ]
18
+ # 부모 노드의 자식에 있는지 확인
19
+ next_link = node .links .get (ch )
20
+
21
+ if not next_link :
22
+ node .links [ch ] = TrieNode ()
23
+ next_link = node .links [ch ]
24
+
25
+ self ._recurAdd (next_link , word [1 :])
26
+
27
+ def insert (self , word : str ) -> None :
28
+ if not word :
29
+ return
30
+
31
+ self ._recurAdd (self ._root , word )
32
+
33
+ def _recurSearch (self , node : TrieNode , word : str ) -> bool :
34
+ if not word :
35
+ return node .isEnd
36
+
37
+ ch = word [0 ]
38
+ next_link = node .links .get (ch )
39
+ if next_link :
40
+ return self ._recurSearch (next_link , word [1 :])
41
+ return False
42
+
43
+ def search (self , word : str ) -> bool :
44
+ if not word :
45
+ return False
46
+
47
+ return self ._recurSearch (self ._root , word )
48
+
49
+ def startsWith (self , prefix : str ) -> bool :
50
+ node = self ._root
51
+ for ch in prefix :
52
+ if ch not in node .links :
53
+ return False
54
+ node = node .links [ch ]
55
+ return True
56
+
57
+ # Your Trie object will be instantiated and called as such:
58
+ # obj = Trie()
59
+ # obj.insert(word)
60
+ # param_2 = obj.search(word)
61
+ # param_3 = obj.startsWith(prefix)
You can’t perform that action at this time.
0 commit comments