File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ 풀이
3
+ - Trie 자료구조 구현을 따릅니다
4
+
5
+ Big O
6
+ - N: 이전까지 insert한 word의 수
7
+ - W: 현재 insert하거나 search하려는 word의 길이
8
+ - P: 현재 startsWith하려는 prefix의 길이
9
+
10
+ - insert
11
+ - Time complexity: O(W)
12
+ - word를 구성하는 모든 문자에 대해 현재 Trie에 저장 여부를 검사합니다
13
+ 해시맵 자료구조를 사용하고 있기에 검색과 삽입 모두 constant 시간 복잡도를 가집니다
14
+ - Space complexity: O(W)
15
+ - 최악의 경우 모든 문자를 Trie에 새롭게 추가할 수 있습니다
16
+ - search
17
+ - Time complexity: O(W)
18
+ - insert와 같습니다
19
+ - Space complexity: O(1)
20
+ - startsWith
21
+ - Time complexity: O(P)
22
+ - search와 같습니다
23
+ - Space complexity: O(1)
24
+ '''
25
+
26
+ class Trie :
27
+
28
+ def __init__ (self ):
29
+ self .root = {}
30
+
31
+ def insert (self , word : str ) -> None :
32
+ parent = self .root
33
+
34
+ for c in word :
35
+ if c not in parent :
36
+ parent [c ] = {}
37
+ parent = parent [c ]
38
+
39
+ parent ["word" ] = word
40
+
41
+ def search (self , word : str ) -> bool :
42
+ parent = self .root
43
+
44
+ for c in word :
45
+ if c not in parent :
46
+ return False
47
+ parent = parent [c ]
48
+
49
+ return "word" in parent and parent ["word" ] == word
50
+
51
+
52
+ def startsWith (self , prefix : str ) -> bool :
53
+ parent = self .root
54
+
55
+ for c in prefix :
56
+ if c not in parent :
57
+ return False
58
+ parent = parent [c ]
59
+
60
+ return True
61
+
62
+
63
+
64
+ # Your Trie object will be instantiated and called as such:
65
+ # obj = Trie()
66
+ # obj.insert(word)
67
+ # param_2 = obj.search(word)
68
+ # param_3 = obj.startsWith(prefix)
You can’t perform that action at this time.
0 commit comments