File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
3
+ * Example:
4
+ * Input: S = "ADOBECODEBANC", T = "ABC"
5
+ * Output: "BANC"
6
+ * Note:
7
+ * If there is no such window in S that covers all characters in T, return the empty string "".
8
+ * If there is such window, you are guaranteed that there will always be only one unique minimum window in S.} s
9
+ */
10
+
11
+ /**
12
+ * @param {string } s
13
+ * @param {string } t
14
+ * @return {string }
15
+ */
16
+ var minWindow = function ( s , t ) {
17
+ const letterMap = { }
18
+ let minLen = Infinity ,
19
+ left = 0 ,
20
+ cnt = 0 ,
21
+ res = ''
22
+ for ( let v of t ) {
23
+ if ( letterMap [ v ] !== undefined ) letterMap [ v ] = ++ letterMap [ v ]
24
+ else letterMap [ v ] = 1
25
+ }
26
+ for ( let i = 0 ; i < s . length ; i ++ ) {
27
+ if ( -- letterMap [ s [ i ] ] >= 0 ) cnt ++
28
+ while ( cnt === t . length ) {
29
+ const localLen = i - left + 1
30
+ if ( minLen > localLen ) {
31
+ minLen = localLen
32
+ res = s . substr ( left , minLen )
33
+ }
34
+ if ( ++ letterMap [ s [ left ] ] > 0 ) cnt --
35
+ left ++
36
+ }
37
+
38
+ }
39
+ return res
40
+ } ;
You can’t perform that action at this time.
0 commit comments