File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ class WordDictionary {
2
+ root : {
3
+ [ key : string ] : any ;
4
+ } ;
5
+
6
+ constructor ( ) {
7
+ this . root = { $ : true } ; // ending
8
+ }
9
+
10
+ // {
11
+ // "$": true,
12
+ // "b": {
13
+ // "$": false,
14
+ // "a": {
15
+ // "$": false,
16
+ // "d": {
17
+ // "$": true
18
+ // }
19
+ // }
20
+ // }
21
+ // }
22
+
23
+ // TC: O(w)
24
+ // SC: O(w)
25
+ addWord ( word : string ) : void {
26
+ let node = this . root ;
27
+
28
+ for ( const ch of word ) {
29
+ if ( ! node [ ch ] ) {
30
+ node [ ch ] = { $ : false } ;
31
+ }
32
+ node = node [ ch ] ;
33
+ }
34
+
35
+ node [ "$" ] = true ;
36
+ }
37
+
38
+ // TC: O(26^w)
39
+ // SC: O(w)
40
+ search ( word : string ) : boolean {
41
+ const dfs = ( node , idx : number ) => {
42
+ if ( idx === word . length ) {
43
+ return node [ "$" ] ;
44
+ }
45
+
46
+ const ch = word [ idx ] ;
47
+
48
+ if ( node [ ch ] ) {
49
+ return dfs ( node [ ch ] , idx + 1 ) ;
50
+ }
51
+
52
+ if ( ch === "." ) {
53
+ for ( const key of Object . keys ( node ) ) {
54
+ if ( key !== "$" && dfs ( node [ key ] , idx + 1 ) ) {
55
+ return true ;
56
+ }
57
+ }
58
+ }
59
+
60
+ return false ;
61
+ } ;
62
+
63
+ return dfs ( this . root , 0 ) ;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Your WordDictionary object will be instantiated and called as such:
69
+ * var obj = new WordDictionary()
70
+ * obj.addWord(word)
71
+ * var param_2 = obj.search(word)
72
+ */
73
+
You can’t perform that action at this time.
0 commit comments