File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+ class TrieNode :
4
+ def __init__ (self ):
5
+ self .children = {}
6
+ self .isEnd = False
7
+
8
+ class Trie :
9
+
10
+ def __init__ (self ):
11
+ self .root = TrieNode ()
12
+
13
+ def insert (self , word : str ) -> None :
14
+ node = self .root
15
+ for ch in word :
16
+ if ch not in node .children :
17
+ node .children [ch ] = TrieNode ()
18
+ node = node .children [ch ]
19
+ node .isEnd = True
20
+
21
+ def search (self , word : str ) -> bool :
22
+ node = self .root
23
+ for ch in word :
24
+ if ch not in node .children :
25
+ return False
26
+ node = node .children [ch ]
27
+ return node .isEnd
28
+
29
+ def startsWith (self , prefix : str ) -> bool :
30
+ node = self .root
31
+ for ch in prefix :
32
+ if ch not in node .children :
33
+ return False
34
+ node = node .children [ch ]
35
+ return True
36
+
37
+ if __name__ == "__main__" :
38
+ trie = Trie ()
39
+
40
+ # insert & search 테스트
41
+ trie .insert ("apple" )
42
+ print (trie .search ("apple" )) # True
43
+ print (trie .search ("app" )) # False
44
+ print (trie .startsWith ("app" )) # True
45
+
46
+ trie .insert ("app" )
47
+ print (trie .search ("app" )) # True
48
+
49
+ # 추가 케이스
50
+ trie .insert ("application" )
51
+ print (trie .search ("application" )) # True
52
+ print (trie .startsWith ("appl" )) # True
53
+ print (trie .search ("apply" )) # False
54
+
55
+ trie .insert ("bat" )
56
+ trie .insert ("bath" )
57
+ print (trie .search ("bat" )) # True
58
+ print (trie .startsWith ("ba" )) # True
59
+ print (trie .search ("bad" )) # False
You can’t perform that action at this time.
0 commit comments