1
1
class WordDictionary {
2
- wordList : Set < string > ;
3
- wordCountMap : Map < number , string [ ] > ;
2
+ wordCountMap : Map < number , Set < string > > ;
4
3
constructor ( ) {
5
- this . wordList = new Set ( ) ;
6
4
this . wordCountMap = new Map ( ) ;
7
5
}
8
6
9
7
// TC: O(1)
10
8
// SC: O(n)
11
9
addWord ( word : string ) : void {
12
- this . wordList . add ( word ) ;
13
10
const length = word . length ;
14
11
if ( this . wordCountMap . has ( length ) ) {
15
- this . wordCountMap . get ( length ) . push ( word ) ;
12
+ this . wordCountMap . get ( length ) . add ( word ) ;
16
13
} else {
17
- this . wordCountMap . set ( length , [ word ] ) ;
14
+ this . wordCountMap . set ( length , new Set ( [ word ] ) ) ;
18
15
}
19
16
return null ;
20
17
}
@@ -26,15 +23,18 @@ class WordDictionary {
26
23
const targetWord = word . replace ( / \. / g, "" ) ;
27
24
const hasDot = len - targetWord . length !== 0 ;
28
25
29
- if ( ! hasDot ) return this . wordList . has ( word ) ;
30
26
if ( ! this . wordCountMap . has ( len ) ) {
31
27
return false ;
32
28
}
33
29
const words = this . wordCountMap . get ( len ) ;
34
- for ( let i = 0 ; i < words . length ; i ++ ) {
30
+ if ( ! hasDot ) {
31
+ return words . has ( word ) ;
32
+ }
33
+
34
+ for ( const w of words ) {
35
35
let match = true ;
36
- for ( let j = 0 ; j < words [ i ] . length ; j ++ ) {
37
- if ( word [ j ] !== "." && word [ j ] !== words [ i ] [ j ] ) {
36
+ for ( let j = 0 ; j < w . length ; j ++ ) {
37
+ if ( word [ j ] !== "." && word [ j ] !== w [ j ] ) {
38
38
match = false ;
39
39
break ;
40
40
}
0 commit comments