File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ var minWindow = function ( str , target ) {
2+ const hash = target . split ( '' ) . reduce ( ( acc , val ) => {
3+ if ( ! acc [ val ] ) acc [ val ] = 0 ;
4+ acc [ val ] += 1 ;
5+ return acc ;
6+ } , { } )
7+
8+ let start = 0 ;
9+ let min = Infinity ;
10+ let matched = 0 ;
11+ let subStringStart = null ;
12+
13+ for ( let i = 0 ; i < str . length ; i ++ ) {
14+ let rightChar = str [ i ] ;
15+
16+ if ( rightChar in hash ) hash [ rightChar ] -= 1 ;
17+ if ( hash [ rightChar ] >= 0 ) matched += 1 ;
18+
19+ while ( matched === target . length ) {
20+ if ( i - start + 1 < min ) {
21+ subStringStart = start ;
22+ min = i - start + 1 ;
23+ }
24+
25+ let leftChar = str [ start ] ;
26+ start += 1 ;
27+
28+ if ( leftChar in hash ) {
29+ if ( hash [ leftChar ] === 0 ) matched -= 1 ;
30+ hash [ leftChar ] += 1 ;
31+ }
32+ }
33+ }
34+ return min === Infinity ? '' : str . substring ( subStringStart , subStringStart + min ) ;
35+ } ;
You can’t perform that action at this time.
0 commit comments