forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
91 lines (70 loc) · 2.13 KB
/
main2.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
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
86
87
88
89
90
91
/// Source : https://leetcode.com/problems/minimum-window-substring/
/// Author : liuyubobobo
/// Time : 2018-08-28
#include <iostream>
#include <cassert>
#include <unordered_set>
#include <vector>
using namespace std;
/// Sliding Window
/// Using filtered s, which remove all characters not in T
/// will be a good improvement when T is small and lots of character are not in S:)
///
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
string minWindow(string s, string t) {
unordered_set<char> t_set;
int tFreq[256] = {0};
for(char c: t){
t_set.insert(c);
tFreq[c] ++;
}
string filtered_s = "";
vector<int> pos;
for(int i = 0; i < s.size() ; i ++)
if(t_set.find(s[i]) != t_set.end()){
filtered_s += s[i];
pos.push_back(i);
}
int sFreq[256] = {0};
int sCnt = 0;
int minLength = s.size() + 1;
int startIndex = -1;
int l = 0, r = -1;
while(l < filtered_s.size()){
if(r + 1 < filtered_s.size() && sCnt < t.size()){
sFreq[filtered_s[r+1]] ++;
if(sFreq[filtered_s[r+1]] <= tFreq[filtered_s[r+1]])
sCnt ++;
r ++;
}
else{
assert(sCnt <= t.size());
if(sCnt == t.size() && pos[r] - pos[l] + 1 < minLength){
minLength = pos[r] - pos[l] + 1;
startIndex = pos[l];
}
sFreq[filtered_s[l]] --;
if(sFreq[filtered_s[l]] < tFreq[filtered_s[l]])
sCnt --;
l ++;
}
}
if( startIndex != -1 )
return s.substr(startIndex, minLength);
return "";
}
};
int main() {
cout << Solution().minWindow("ADOBECODEBANC", "ABC") << endl;
// BANC
cout << Solution().minWindow("a", "aa") << endl;
// empty
cout << Solution().minWindow("aa", "aa") << endl;
// aa
cout << Solution().minWindow("bba", "ab") << endl;
// ba
return 0;
}