-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumWindowSubstring.cpp
More file actions
58 lines (48 loc) · 1.38 KB
/
MinimumWindowSubstring.cpp
File metadata and controls
58 lines (48 loc) · 1.38 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
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <climits>
using namespace std;
class Solution {
public:
string minWindow(const string& s, const string& t) {
if (s.size() < t.size()) return "";
unordered_map<char, int> mp;
for (auto a : t) {
mp[a]++;
}
int satisfied = 0;
unordered_map<char, int> tmp;
int l = 0;
int startIdx = -1;
int minLen = INT_MAX;
for (int r = 0; r < s.size(); r++) {
char addChar = s[r];
tmp[addChar]++;
if (mp.count(addChar) && tmp[addChar] == mp[addChar]) {
satisfied++;
}
while (satisfied == mp.size()) {
if (r - l + 1 < minLen) {
minLen = r - l + 1;
startIdx = l;
}
char removeChar = s[l];
if (mp.count(removeChar) && tmp[removeChar] == mp[removeChar]) {
satisfied--;
}
tmp[removeChar]--;
l++;
}
}
return (startIdx == -1) ? "" : s.substr(startIdx, minLen);
}
};
int main() {
Solution sol;
cout << sol.minWindow("ADOBECODEBANC", "ABC") << endl;
cout << sol.minWindow("a", "a") << endl;
cout << sol.minWindow("a", "aa") << endl;
return 0;
}