11class WordDictionary {
2- wordList : Set < string > ;
3- wordCountMap : Map < number , string [ ] > ;
2+ wordCountMap : Map < number , Set < string > > ;
43 constructor ( ) {
5- this . wordList = new Set ( ) ;
64 this . wordCountMap = new Map ( ) ;
75 }
86
97 // TC: O(1)
108 // SC: O(n)
119 addWord ( word : string ) : void {
12- this . wordList . add ( word ) ;
1310 const length = word . length ;
1411 if ( this . wordCountMap . has ( length ) ) {
15- this . wordCountMap . get ( length ) . push ( word ) ;
12+ this . wordCountMap . get ( length ) . add ( word ) ;
1613 } else {
17- this . wordCountMap . set ( length , [ word ] ) ;
14+ this . wordCountMap . set ( length , new Set ( [ word ] ) ) ;
1815 }
1916 return null ;
2017 }
@@ -26,15 +23,18 @@ class WordDictionary {
2623 const targetWord = word . replace ( / \. / g, "" ) ;
2724 const hasDot = len - targetWord . length !== 0 ;
2825
29- if ( ! hasDot ) return this . wordList . has ( word ) ;
3026 if ( ! this . wordCountMap . has ( len ) ) {
3127 return false ;
3228 }
3329 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 ) {
3535 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 ] ) {
3838 match = false ;
3939 break ;
4040 }
0 commit comments