-
Notifications
You must be signed in to change notification settings - Fork 12
/
MinimumWindowSubstring.cpp
38 lines (37 loc) · 1021 Bytes
/
MinimumWindowSubstring.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
#include "LeetCode.h"
class Solution {
public:
// cost too much time
string minWindow(string S, string T) {
unordered_map<char, int> limit;
for (char c : T) {
limit.insert(make_pair(c, 0)).first->second++;
}
int head = 0, tail = 0;
int minh = 0, mint = INT_MAX;
int count = 0;
int size = S.size();
while(head < size) {
for(;tail<size && count < limit.size(); tail++) {
if (limit.find(S[tail]) != limit.end()) {
limit[S[tail]]--;
if (limit[S[tail]] == 0) {
count++;
}
}
}
if (count == limit.size() && tail-head < mint-minh) {
tie(minh, mint) = tie(head, tail);
}
if (limit.find(S[head]) != limit.end()) {
if (limit[S[head]] == 0) count--;
limit[S[head]]++;
}
head++;
if (count == limit.size() && tail-head < mint-minh) {
tie(minh, mint) = tie(head, tail);
}
}
return mint != INT_MAX? S.substr(minh, mint-minh):string();
}
};