forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0076-minimum-window-substring.cpp
62 lines (52 loc) · 1.57 KB
/
0076-minimum-window-substring.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
Given 2 strings s & t, return min window substring
of s such that all chars in t are included in window
Ex. s = "ADOBECODEBANC" t = "ABC" -> "BANC"
Sliding window + hash map {char -> count}
Move j until valid, move i to find smaller
Time: O(m + n)
Space: O(m + n)
*/
class Solution {
public:
string minWindow(string s, string t) {
// count of char in t
unordered_map<char, int> m;
for (int i = 0; i < t.size(); i++) {
m[t[i]]++;
}
int i = 0;
int j = 0;
// # of chars in t that must be in s
int counter = t.size();
int minStart = 0;
int minLength = INT_MAX;
while (j < s.size()) {
// if char in s exists in t, decrease
if (m[s[j]] > 0) {
counter--;
}
// if char doesn't exist in t, will be -'ve
m[s[j]]--;
// move j to find valid window
j++;
// when window found, move i to find smaller
while (counter == 0) {
if (j - i < minLength) {
minStart = i;
minLength = j - i;
}
m[s[i]]++;
// when char exists in t, increase
if (m[s[i]] > 0) {
counter++;
}
i++;
}
}
if (minLength != INT_MAX) {
return s.substr(minStart, minLength);
}
return "";
}
};