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
+ * [Problem]: [208] Implement Trie (Prefix Tree)
3
+ * (https://leetcode.com/problems/implement-trie-prefix-tree/description/)
4
+ */
5
+
6
+ class TrieNode {
7
+ children : { [ key : string ] : TrieNode } ;
8
+ isEnd : boolean ;
9
+
10
+ constructor ( ) {
11
+ this . children = { } ;
12
+ this . isEnd = false ;
13
+ }
14
+ }
15
+
16
+ class Trie {
17
+ constructor ( private root = new TrieNode ( ) ) { }
18
+
19
+ //시간복잡도: O(n)
20
+ //공간복잡도: O(n)
21
+ insert ( word : string ) : void {
22
+ let node = this . root ;
23
+ for ( let char of word ) {
24
+ if ( ! node . children [ char ] ) {
25
+ node . children [ char ] = new TrieNode ( ) ;
26
+ }
27
+
28
+ node = node . children [ char ] ;
29
+ }
30
+
31
+ node . isEnd = true ;
32
+ }
33
+
34
+ //시간복잡도: O(n)
35
+ //공간복잡도: O(n)
36
+ search ( word : string ) : boolean {
37
+ let node = this . root ;
38
+ for ( let char of word ) {
39
+ if ( ! node . children [ char ] ) return false ;
40
+ node = node . children [ char ] ;
41
+ }
42
+
43
+ return node . isEnd ;
44
+ }
45
+
46
+ //시간복잡도: O(n)
47
+ //공간복잡도: O(n)
48
+ startsWith ( prefix : string ) : boolean {
49
+ let node = this . root ;
50
+ for ( let char of prefix ) {
51
+ if ( ! node . children [ char ] ) return false ;
52
+ node = node . children [ char ] ;
53
+ }
54
+
55
+ return true ;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Your Trie object will be instantiated and called as such:
61
+ * var obj = new Trie()
62
+ * obj.insert(word)
63
+ * var param_2 = obj.search(word)
64
+ * var param_3 = obj.startsWith(prefix)
65
+ */
You can’t perform that action at this time.
0 commit comments