-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0076-minimum-window-substring.cpp
More file actions
59 lines (47 loc) · 1.23 KB
/
Copy path0076-minimum-window-substring.cpp
File metadata and controls
59 lines (47 loc) · 1.23 KB
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
#include <string>
#include <unordered_map>
class Solution {
public:
string minWindow(string s, string t) {
string EMPTY = "";
if (s.size() < t.size()) {
return EMPTY;
}
unordered_map<char, int> counts;
unordered_map<char, int> window;
for (char c : t) {
counts[c] += 1;
}
int have = 0;
int need = counts.size();
int windowSize = s.size() + 999;
int left = 0;
int committedLeft = -1;
int committedRight = -1;
for (int right = 0; right < s.size(); right++) {
char c = s[right];
window[c] += 1;
if (counts.find(c) != counts.end() && window[c] == counts[c]) {
have++;
}
while (need == have) {
int currentWindowSize = right - left + 1;
if (currentWindowSize < windowSize) {
committedLeft = left;
committedRight = right;
windowSize = currentWindowSize;
}
window[s[left]] -= 1;
if (counts.find(s[left]) != counts.end() &&
window[s[left]] < counts[s[left]]) {
have -= 1;
}
left += 1;
}
}
if (windowSize > s.size()) {
return EMPTY;
}
return s.substr(committedLeft, committedRight - committedLeft + 1);
}
};