File tree 1 file changed +59
-0
lines changed
implement-trie-prefix-tree
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Solution:
3
+ Trie 구조에 대해 배워보았습니다.
4
+ TrieNode 는 children과 ending으로 이루어져있습니다.
5
+ 1) insert:
6
+ 1.1) 문자열의 각 문자를 Trie 구조에 넣습니다.
7
+ 1.2) 마지막 문자열에선 ending 을 True 로 set합니다.
8
+ 2) search:
9
+ 2.1) 문자열의 각 문자가 node.children 에 존재하지 않으면 False 를 반환합니다.
10
+ 2.2) 마지막 문자가 ending 인지 판별합니다.
11
+ 3) startsWith
12
+ 3.1) search 와 동일하게 문자열을 순회합니다.
13
+ 3.2) ending 여부와 무관하게 True 를 반환합니다.
14
+ """
15
+
16
+
17
+ class TrieNode :
18
+ def __init__ (self ):
19
+ self .children = {}
20
+ self .ending = False
21
+
22
+
23
+ class Trie :
24
+ def __init__ (self ):
25
+ self .root = TrieNode ()
26
+
27
+ def insert (self , word : str ) -> None :
28
+ node = self .root
29
+
30
+ for char in word :
31
+ if char not in node .children :
32
+ node .children [char ] = TrieNode ()
33
+ node = node .children [char ]
34
+ node .ending = True
35
+
36
+ def search (self , word : str ) -> bool :
37
+ node = self .root
38
+
39
+ for char in word :
40
+ if char not in node .children :
41
+ return False
42
+ node = node .children [char ]
43
+ return node .ending
44
+
45
+ def startsWith (self , prefix : str ) -> bool :
46
+ node = self .root
47
+
48
+ for char in prefix :
49
+ if char not in node .children :
50
+ return False
51
+ node = node .children [char ]
52
+ return True
53
+
54
+
55
+ # Your Trie object will be instantiated and called as such:
56
+ # obj = Trie()
57
+ # obj.insert(word)
58
+ # param_2 = obj.search(word)
59
+ # param_3 = obj.startsWith(prefix)
You can’t perform that action at this time.
0 commit comments