-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminWindow.cpp
More file actions
executable file
·74 lines (59 loc) · 1.77 KB
/
minWindow.cpp
File metadata and controls
executable file
·74 lines (59 loc) · 1.77 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
/*Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
*/
/* Idea
1. use two tables to record the number of chars in T to be found, and found
2. two points
*/
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <climits>
using namespace std;
string minWindow(string S, string T) {
int sn = S.size();
int tn = T.size();
if(tn > sn) return "";
int needToFound[256] = {0};
int Filled[256] = {0};
int subwin = INT_MAX;
int count = 0;
for(int i = 0; i < tn; ++i)
needToFound[T[i]] ++;
int wb = 0;
for(int bg =0, pos = 0; pos < sn; ++pos){
if(needToFound[S[pos]] == 0) continue;
Filled[S[pos]] ++;
if(Filled[S[pos]] <= needToFound[S[pos]])
count ++;
if(count == tn){
while(Filled[S[bg]] == 0 || Filled[S[bg]] > needToFound[S[bg]]){
if(Filled[S[bg]] > needToFound[S[bg]])
Filled[S[bg]] --;
bg++;
}
if(subwin > pos - bg + 1){
subwin = pos - bg + 1;
wb = bg;
}
}
}
if(count < tn)
return "";
else
return S.substr(wb,subwin);
}
int main(int argc, char const *argv[])
{
string S = "ABC";
string T = "B";
cout << minWindow(S,T) <<endl;
return 0;
}