-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path076_min_window.cpp
More file actions
52 lines (48 loc) · 1.48 KB
/
Copy path076_min_window.cpp
File metadata and controls
52 lines (48 loc) · 1.48 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
//
// Created by wangxiaobo on 2020/6/27.
//
#include <utils.h>
// sliding window
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> map;
for (auto c : t) map[c]++;
int left = 0, cnt = 0, maxlen = s.size() + 1, start = left;
for (int i = 0; i < s.size(); ++i) {
if (--map[s[i]] >= 0) ++cnt;
while(cnt == t.size()) {
if (maxlen > i - left + 1) {
maxlen = i - left + 1;
start = left;
}
if (++map[s[left]] > 0) cnt--;
left++;
}
}
return maxlen == s.size() + 1 ? "" : s.substr(start, maxlen);
}
string minWindow2(string s, string t) {
unordered_map<char, int> map;
for (auto c : t) map[c]++;
int left = 0, cnt = 0, maxlen = s.size() + 1, start = left;
for (int i = 0; i < s.size(); ++i) {
if (--map[s[i]] >= 0) ++cnt;
while (cnt == t.size()) {
if (++map[s[left]] > 0) {
if (maxlen > i - left + 1) {
maxlen = i - left + 1;
start = left;
}
cnt--;
}
left++;
}
}
return maxlen == s.size() + 1 ? "" : s.substr(start, maxlen);
}
};
TEST(_0076, minWindow) {
Solution sln;
ASSERT_EQ(sln.minWindow2("ADOBECODEBANC", "ABC"), "BANC");
}