@@ -15,6 +15,7 @@ If there is no such window in S that covers all characters in T, return the empt
1515If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
1616*/
1717
18+ // Solution 1
1819var minWindow = function ( s , t ) {
1920 if ( t . length === 0 || s . length < t . length ) return "" ;
2021
@@ -67,4 +68,64 @@ var getHash = function (t) {
6768 return hash ;
6869} ;
6970
71+
72+
73+ // Solution 2
74+ // Similar idea code slightly different;
75+ var buildHash = function ( t ) {
76+ let hash = { } ;
77+ let occ = 0 ;
78+ for ( var i = 0 ; i < t . length ; i ++ ) {
79+ occ = hash [ t [ i ] ] == undefined ? 0 : hash [ t [ i ] ] ;
80+ hash [ t [ i ] ] = occ + 1 ;
81+ }
82+ return hash ;
83+ }
84+
85+ var minWindow2 = function ( s , t ) {
86+ var hashT = buildHash ( t ) ;
87+ var start = 0 ;
88+ var end = 0 ;
89+ var countLeft = t . length ;
90+ var minWindow = "" ;
91+ var minWindowLeft = - 1 ;
92+ var maxWindowRight = - 1 ;
93+
94+ while ( start < s . length && end < s . length ) {
95+ if ( countLeft > 0 ) { // window does not contain all elements
96+ if ( hashT [ s [ end ] ] !== undefined ) {
97+ hashT [ s [ end ] ] = hashT [ s [ end ] ] - 1 ;
98+ if ( hashT [ s [ end ] ] >= 0 ) {
99+ countLeft -- ;
100+ }
101+ }
102+
103+ if ( countLeft > 0 ) {
104+ end ++ ;
105+ }
106+ } else { // found window
107+ if ( minWindowLeft == - 1 || ( ( maxWindowRight - minWindowLeft + 1 ) > ( end - start + 1 ) ) ) {
108+ minWindowLeft = start ;
109+ maxWindowRight = end ;
110+ }
111+ if ( hashT [ s [ start ] ] !== undefined ) {
112+ hashT [ s [ start ] ] = hashT [ s [ start ] ] + 1 ;
113+ if ( hashT [ s [ start ] ] > 0 ) {
114+ countLeft ++ ;
115+ end ++ ;
116+ }
117+ }
118+ start ++ ;
119+ }
120+ }
121+
122+ if ( minWindowLeft > - 1 ) {
123+ return s . substring ( minWindowLeft , maxWindowRight + 1 ) ;
124+ }
125+
126+ return "" ;
127+ } ;
128+
129+
130+
70131module . exports . minWindow = minWindow ;
0 commit comments