-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0076_Minimum_Window_Substring.cpp
More file actions
85 lines (81 loc) · 1.83 KB
/
Copy path0076_Minimum_Window_Substring.cpp
File metadata and controls
85 lines (81 loc) · 1.83 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include<iostream>
#include<string>
#include<unordered_map>
#include<queue>
using namespace std;
class Solution {
public:
string minWindow(string s, string t) {
int n = s.length();
int m = t.length();
int i, j, left, minlen = n + 1, curlen;
char lack;
unordered_map<char, int> map;
unordered_map<char, int>::iterator it;
// bound
if(n == 0 || m == 0) return "";
// init
for(i = 0; i < m; i++){
if(map.find(t[i]) != map.end()){
map[t[i]] += 1;
}
else{
map[t[i]] = 1;
}
}
// find the first satisfied sub string
for(i = 0; i < n; i++){
if(map.find(s[i]) != map.end()){
map[s[i]]--;
break;
}
}
for(j = i, it = map.begin();j < n;){
while(it->second > 0){
j++;
if(j >= n) break;
if(map.find(s[j]) != map.end()) map[s[j]]--;
}
if(it->second > 0) break;
it++;
if(it == map.end()) break;
}
if(it != map.end()) return "";
// left and right pointer
while(true){
curlen = j - i + 1;
if(curlen < minlen){
left = i;
minlen = curlen;
}
// left pointer move to a letter in the T
lack = s[i];
map[lack]++;
i++;
while((i < n) && (map.find(s[i]) == map.end())) i++;
if(i >= n) break;
// if the lack letter not influence the new substring satisfied
if(map[lack] <= 0) continue;
else{
// find the next s[j] == lack to make the new substring satisfied
j++;
while((j < n) && (s[j] != lack)){
if(map.find(s[j]) != map.end()) map[s[j]]--;
j++;
}
if(j >= n) break;
map[lack]--;
}
}
if(minlen > n) return "";
else return s.substr(left, minlen);
}
};
int main(){
string S = "ADOBECODEBANC";
string T = "ABC";
//string S = "aa";
//string T = "aa";
Solution solve;
cout << solve.minWindow(S, T);
}