File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/implement-trie-prefix-tree
3
+ */
4
+ class Trie {
5
+ constructor ( private root : Record < string , any > = { } ) { }
6
+
7
+ insert ( word : string ) : void {
8
+ let node = this . root ;
9
+ for ( const char of word ) {
10
+ if ( ! node [ char ] ) {
11
+ node [ char ] = { } ;
12
+ }
13
+ node = node [ char ] ;
14
+ }
15
+ node . isEnd = true ;
16
+ }
17
+
18
+ search ( word : string ) : boolean {
19
+ let node = this . root ;
20
+ for ( const char of word ) {
21
+ if ( ! node [ char ] ) {
22
+ return false ;
23
+ }
24
+ node = node [ char ] ;
25
+ }
26
+ return ! ! node . isEnd ;
27
+ }
28
+
29
+ startsWith ( prefix : string ) : boolean {
30
+ let node = this . root ;
31
+ for ( const char of prefix ) {
32
+ if ( ! node [ char ] ) {
33
+ return false ;
34
+ }
35
+ node = node [ char ] ;
36
+ }
37
+ return true ;
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Your Trie object will be instantiated and called as such:
43
+ * var obj = new Trie()
44
+ * obj.insert(word)
45
+ * var param_2 = obj.search(word)
46
+ * var param_3 = obj.startsWith(prefix)
47
+ */
You can’t perform that action at this time.
0 commit comments