forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdylan-jung.cpp
More file actions
60 lines (53 loc) · 1.51 KB
/
dylan-jung.cpp
File metadata and controls
60 lines (53 loc) · 1.51 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
60
class Solution {
public:
string minWindow(string s, string t) {
int m = (int)s.size();
if (t.empty() || s.empty()) return "";
int target[128] = {0};
int cnt[128] = {0};
int required = 0;
for (char c : t) {
unsigned char uc = (unsigned char)c;
if (target[uc] == 0) required++;
target[uc]++;
}
int formed = 0;
int l = 0, r = 0;
int ansl = 0, ansr = 0;
bool hasAns = false;
while (l <= r) {
bool isValid = (formed == required);
if (isValid) {
if (!hasAns || (r - l) < (ansr - ansl)) {
ansl = l;
ansr = r;
hasAns = true;
}
char cl = s[l];
cnt[cl]--;
if (target[cl] > 0 && cnt[cl] == target[cl] - 1) {
formed--;
}
l++;
}
else if (r >= m) {
char cl = s[l];
cnt[cl]--;
if (target[cl] > 0 && cnt[cl] == target[cl] - 1) {
formed--;
}
l++;
}
else {
char cr = s[r];
cnt[cr]++;
if (target[cr] > 0 && cnt[cr] == target[cr]) {
formed++;
}
r++;
}
}
if (!hasAns) return "";
return s.substr(ansl, ansr - ansl);
}
};