File tree Expand file tree Collapse file tree 2 files changed +99
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 2 files changed +99
-0
lines changed Original file line number Diff line number Diff line change 1+ # Trie Data Structure 구현
2+ # TC: O(n), SC: O(N)
3+ # autocomplete and spellchecker 등에 사용
4+
5+ class Node :
6+ def __init__ (self , ending = False ):
7+ self .children = {}
8+ self .ending = ending
9+
10+ class Trie :
11+ def __init__ (self ):
12+ self .root = Node (ending = True ) # 노드 객체 생성
13+
14+ def insert (self , word : str ) -> None :
15+ node = self .root #Trie의 최상위 노드부터 시작
16+ for ch in word :
17+ if ch not in node .children :
18+ node .children [ch ] = Node () # 새로운 노드 생성
19+ node = node .children [ch ]
20+ node .ending = True
21+
22+ def search (self , word : str ) -> bool :
23+ node = self .root
24+
25+ for ch in word :
26+ if ch not in node .children :
27+ return False
28+ node = node .children [ch ]
29+ return node .ending
30+
31+ def startsWith (self , prefix : str ) -> bool :
32+ node = self .root
33+
34+ for ch in prefix :
35+ if ch not in node .children :
36+ return False
37+ node = node .children [ch ]
38+ return True
39+
40+
41+ # Your Trie object will be instantiated and called as such:
42+ # obj = Trie()
43+ # obj.insert(word)
44+ # param_2 = obj.search(word)
45+ # param_3 = obj.startsWith(prefix)
Original file line number Diff line number Diff line change 1+ class TrieNode {
2+ children : Map < string , TrieNode > ;
3+ ending : boolean ;
4+
5+ constructor ( ending = false ) {
6+ this . children = new Map ( ) ;
7+ this . ending = ending ;
8+ }
9+ }
10+
11+ class Trie {
12+ private root : TrieNode ;
13+
14+ constructor ( ) {
15+ this . root = new TrieNode ( true ) ;
16+ }
17+
18+ insert ( word : string ) : void {
19+ let node = this . root ;
20+ for ( const ch of word ) {
21+ if ( ! node . children . has ( ch ) ) {
22+ node . children . set ( ch , new TrieNode ( ) ) ;
23+ }
24+ node = node . children . get ( ch ) ! ; // 노드 포인터를 ch로 이동
25+ }
26+ node . ending = true ;
27+ }
28+
29+ search ( word : string ) : boolean {
30+ let node = this . root ;
31+ for ( const ch of word ) {
32+ if ( ! node . children . has ( ch ) ) return false ;
33+ node = node . children . get ( ch ) ! ;
34+ }
35+ return node . ending ;
36+ }
37+
38+ startsWith ( prefix : string ) : boolean {
39+ let node = this . root ;
40+ for ( const ch of prefix ) {
41+ if ( ! node . children . has ( ch ) ) return false ;
42+ node = node . children . get ( ch ) ! ;
43+ }
44+ return true ;
45+ }
46+ }
47+
48+ /**
49+ * Your Trie object will be instantiated and called as such:
50+ * var obj = new Trie()
51+ * obj.insert(word)
52+ * var param_2 = obj.search(word)
53+ * var param_3 = obj.startsWith(prefix)
54+ */
You can’t perform that action at this time.
0 commit comments