forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
minimum-window-substring.cpp
51 lines (43 loc) · 1.39 KB
/
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
// Time: O(n)
// Space: O(k)
class Solution {
public:
string minWindow(string s, string t) {
if (s.empty() || s.length() < t.length()) {
return "";
}
const int ASCII_MAX = 256;
vector<int> exp_cnt(ASCII_MAX, 0);
vector<int> cur_cnt(ASCII_MAX, 0);
int cnt = 0;
int start = 0;
int min_start = 0;
int min_width = numeric_limits<int>::max();
for (const auto& c : t) {
++exp_cnt[c];
}
for (int i = 0; i < s.length(); ++i) {
if (exp_cnt[s[i]] > 0) {
++cur_cnt[s[i]];
if (cur_cnt[s[i]] <= exp_cnt[s[i]]) { // Counting expected elements.
++cnt;
}
}
if (cnt == t.size()) { // If window meets the requirement.
while (exp_cnt[s[start]] == 0 || // Adjust left bound of window.
cur_cnt[s[start]] > exp_cnt[s[start]]) {
--cur_cnt[s[start]];
++start;
}
if (min_width > i - start + 1) { // Update minimum window.
min_width = i - start + 1;
min_start = start;
}
}
}
if (min_width == numeric_limits<int>::max()) {
return "";
}
return s.substr(min_start, min_width);
}
};