-
Notifications
You must be signed in to change notification settings - Fork 28
/
Minimum_Window_Substring.cpp
49 lines (45 loc) · 1.58 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
class Solution {
public:
string minWindow(string s, string t) {
string result;
int m = s.length();
int n = t.length();
if(n > m) return result;
const int MAX = 256;
int freq[MAX] = {0};
int freq2[MAX] = {0};
for(int i = 0; i < n; ++i) {
freq2[t[i]]++;
}
int chars = 0;
int minLen = INT_MAX;
for(int left = 0, right = 0; right < m; ++right) {
if(freq2[s[right]]) {
freq[s[right]]++;
if(freq[s[right]] == freq2[s[right]]) {
chars += freq2[s[right]];
}
if(chars == n) {
for(; left <= right; ++left) {
if(freq2[s[left]]) {
if(freq[s[left]] == freq2[s[left]]) {
int len = right - left + 1;
if(len < minLen) {
minLen = len;
result = s.substr(left, len);
}
chars -= freq2[s[left]];
freq[s[left]]--;
left++;
break;
} else if(freq[s[left]] > freq2[s[left]]) {
freq[s[left]]--;
}
}
}
}
}
}
return result;
}
};