Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a6ea1f6

Browse files
Minimum_Window_Substring.js
1 parent 22fd86c commit a6ea1f6

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
Minimum Window Substring
3+
4+
https://leetcode.com/problems/minimum-window-substring/
5+
6+
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).
7+
8+
Example:
9+
10+
Input: S = "ADOBECODEBANC", T = "ABC"
11+
Output: "BANC"
12+
Note:
13+
14+
If there is no such window in S that covers all characters in T, return the empty string "".
15+
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
16+
*/
17+
18+
19+
var minWindow = function(s, t) {
20+
if(t.length === 0 || s.length < t.length)
21+
return "";
22+
23+
var start = 0;
24+
var end = 0;
25+
var solutionStart, solutionEnd;
26+
var hashT = getHash(t);
27+
var currentHash = {};
28+
var currentCount = 0;
29+
while(end < s.length) {
30+
const letter = s.charAt(end);
31+
if(hashT[letter]) {
32+
currentHash[letter] = (currentHash[letter]) ? currentHash[letter] + 1 : 1;
33+
if(currentHash[letter] <= hashT[letter])
34+
currentCount++;
35+
if(currentCount === t.length) {
36+
while(hashT[s[start]] === undefined || currentHash[s[start]] > hashT[s[start]]) {
37+
if(currentHash[s[start]] !== undefined)
38+
currentHash[s[start]] = currentHash[s[start]] - 1;
39+
40+
start++;
41+
}
42+
if(solutionEnd === undefined || end - start < solutionEnd - solutionStart) {
43+
solutionStart = start;
44+
solutionEnd = end;
45+
}
46+
47+
currentHash[s[start]] = currentHash[s[start]] - 1;
48+
currentCount--;
49+
start++;
50+
}
51+
}
52+
end++;
53+
}
54+
55+
return s.slice(solutionStart, solutionEnd + 1);
56+
};
57+
58+
var getHash = function(t) {
59+
var hash = {};
60+
for(var i = 0; i < t.length; i++) {
61+
const letter = t.charAt(i);
62+
hash[letter] = (hash[letter]) ? hash[letter] + 1 : 1;
63+
}
64+
return hash;
65+
}
66+
67+
var main = function() {
68+
console.log(minWindow("ADOBECODEBANC", "ABC"));
69+
console.log(minWindow("caaec", "cae"));
70+
console.log(minWindow("bbacbb", "ab"));
71+
console.log(minWindow("abba", "b"));
72+
console.log(minWindow("abba", "a"));
73+
console.log(minWindow("abba", ""));
74+
}
75+
76+
module.exports.main

0 commit comments

Comments
 (0)