File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ 풀이 : 딕셔너리를 통해 트리구현
3
+ - 생성자 함수는 맨 처음 노드를 만드는 역할, search("")를 위해 "ending":True로 초기화
4
+ - insert함수를 수행하면 노드는 다음 문자에 대해서도 각각 노드를 가지고 있음
5
+ ex) insert("a"); insert("b")
6
+ {
7
+ "ending":True,
8
+ "a" :{"ending":True},
9
+ "b" :{"ending":True}
10
+ }
11
+ - insert(): word의 순서대로 다음 문자의 노드(존재하지 않으면 {"ending":False}로 초기화)로 이동함
12
+ for문 끝난 후 마지막 문자에서는 해당 노드로 끝나는 단어가 있다는 의미로 "ending":True로 수정
13
+
14
+ - search(): word 다음 문자의 노드로 이동하면서 존재하지 않으면 return False
15
+ 문자의 끝에 도달하면 끝나는 단어가 있는지 node["ending"] return
16
+
17
+ - startsWith(): prefix 다음 문자의 노드로 이동하면서 존재하지 않으면 return False
18
+ 문자의 끝에 도달하면 return True
19
+
20
+ TC : O(N)
21
+ 단어의 길이(N)에 비례한다
22
+ SC : O(N)
23
+ insert할 단어의 길이(N)에 비례해서 노드가 생성된다
24
+
25
+ - 딕셔너리가 아닌 class로 풀이할 수도 있다
26
+ """
27
+
28
+ class Trie :
29
+
30
+ def __init__ (self ):
31
+ self .root = {"ending" :True }
32
+
33
+ def insert (self , word : str ) -> None :
34
+ node = self .root
35
+ for char in word :
36
+ if char not in node :
37
+ node [char ] = {"ending" : False }
38
+ node = node [char ]
39
+ node ["ending" ] = True
40
+
41
+ def search (self , word : str ) -> bool :
42
+ node = self .root
43
+ for char in word :
44
+ if char in node :
45
+ node = node [char ]
46
+ else :
47
+ return False
48
+ return node ["ending" ]
49
+
50
+
51
+ def startsWith (self , prefix : str ) -> bool :
52
+ node = self .root
53
+ for char in prefix :
54
+ if char in node :
55
+ node = node [char ]
56
+ else :
57
+ return False
58
+ return True
59
+
60
+
61
+ # Your Trie object will be instantiated and called as such:
62
+ # obj = Trie()
63
+ # obj.insert(word)
64
+ # param_2 = obj.search(word)
65
+ # param_3 = obj.startsWith(prefix)
You can’t perform that action at this time.
0 commit comments