File tree 1 file changed +75
-0
lines changed
1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ // n: len(s), m: len(t)
2
+ // Time complexity: O(n+m)
3
+ // Space complexity: O(n+m)
4
+
5
+ /**
6
+ * @param {string } s
7
+ * @param {string } t
8
+ * @return {string }
9
+ */
10
+ var minWindow = function ( s , t ) {
11
+ let i = 0 ;
12
+ let j = 0 ;
13
+
14
+ const current = new Map ( ) ;
15
+ const target = new Map ( ) ;
16
+
17
+ current . set ( s [ i ] , 1 ) ;
18
+
19
+ for ( const chr of t ) {
20
+ if ( target . has ( chr ) ) {
21
+ target . set ( chr , target . get ( chr ) + 1 ) ;
22
+ continue ;
23
+ }
24
+
25
+ target . set ( chr , 1 ) ;
26
+ }
27
+
28
+ let answer = null ;
29
+
30
+ while ( i < s . length ) {
31
+ let pass = true ;
32
+ for ( const [ key , value ] of target ) {
33
+ if ( ! current . has ( key ) ) {
34
+ pass = false ;
35
+ break ;
36
+ }
37
+
38
+ if ( current . get ( key ) < value ) {
39
+ pass = false ;
40
+ break ;
41
+ }
42
+ }
43
+
44
+ if ( pass ) {
45
+ if ( ! answer ) {
46
+ answer = s . slice ( i , j + 1 ) ;
47
+ }
48
+
49
+ if ( answer && j - i + 1 < answer . length ) {
50
+ answer = s . slice ( i , j + 1 ) ;
51
+ }
52
+
53
+ current . set ( s [ i ] , current . get ( s [ i ] ) - 1 ) ;
54
+ if ( current . get ( s [ i ] ) === 0 ) {
55
+ current . delete ( s [ i ] ) ;
56
+ }
57
+ i ++ ;
58
+
59
+ continue ;
60
+ }
61
+
62
+ if ( j < s . length ) {
63
+ j ++ ;
64
+ current . set ( s [ j ] , ( current . get ( s [ j ] ) || 0 ) + 1 ) ;
65
+ } else {
66
+ break ;
67
+ }
68
+ }
69
+
70
+ if ( answer === null ) {
71
+ return "" ;
72
+ }
73
+
74
+ return answer ;
75
+ } ;
You can’t perform that action at this time.
0 commit comments