File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ class WordDictionary {
2
+ wordList : Set < string > ;
3
+ wordCountMap : Map < number , string [ ] > ;
4
+ constructor ( ) {
5
+ this . wordList = new Set ( ) ;
6
+ this . wordCountMap = new Map ( ) ;
7
+ }
8
+
9
+ // TC: O(1)
10
+ // SC: O(n)
11
+ addWord ( word : string ) : void {
12
+ this . wordList . add ( word ) ;
13
+ const length = word . length ;
14
+ if ( this . wordCountMap . has ( length ) ) {
15
+ this . wordCountMap . get ( length ) . push ( word ) ;
16
+ } else {
17
+ this . wordCountMap . set ( length , [ word ] ) ;
18
+ }
19
+ return null ;
20
+ }
21
+
22
+ // TC: O(m*n) // m: words length, n: word length
23
+ // SC: O(1)
24
+ search ( word : string ) : boolean {
25
+ const len = word . length ;
26
+ const targetWord = word . replace ( / \. / g, "" ) ;
27
+ const hasDot = len - targetWord . length !== 0 ;
28
+
29
+ if ( ! hasDot ) return this . wordList . has ( word ) ;
30
+ if ( ! this . wordCountMap . has ( len ) ) {
31
+ return false ;
32
+ }
33
+ const words = this . wordCountMap . get ( len ) ;
34
+ for ( let i = 0 ; i < words . length ; i ++ ) {
35
+ let match = true ;
36
+ for ( let j = 0 ; j < words [ i ] . length ; j ++ ) {
37
+ if ( word [ j ] !== "." && word [ j ] !== words [ i ] [ j ] ) {
38
+ match = false ;
39
+ break ;
40
+ }
41
+ }
42
+ if ( match ) {
43
+ return true ;
44
+ }
45
+ }
46
+ return false ;
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments