-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumWindowSubstring.cpp
More file actions
53 lines (49 loc) · 1.61 KB
/
MinimumWindowSubstring.cpp
File metadata and controls
53 lines (49 loc) · 1.61 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
/***
* 双指针 动态维护一个区间
* 尾指针不断往后扫,当扫到有一个窗口包含所有的T的字符后
* 收缩头指针,直到不能再收缩
* 最后记录最小的窗口
* 用两个计数器分别记录S T中的字母数,同时记录匹配的个数
***/
class Solution {
public:
string minWindow(string S, string T) {
if (S.empty() || (S.size() < T.size()))
return "";
int cnts[256] = {0}; // count of S
int cntt[256] = {0}; // count of T
for (int i = 0; i < T.size(); ++i)
++cntt[T[i]];
int minw = INT_MAX;
int mins = 0; // start of min window
int wstart = 0; // start of window
int cntm = 0; // count of matched alpha
for (int wend = 0; wend < S.size(); ++wend) // sliding window
{
if (cntt[S[wend]] > 0) // S[wend] is in T
{
++cnts[S[wend]];
if (cnts[S[wend]] <= cntt[S[wend]]) // one more matched alpha
++cntm;
}
if (cntm == T.size()) // get a matched window
{
while ((cnts[S[wstart]] > cntt[S[wstart]]) || (0 == cntt[S[wstart]])) // narrow the window
{
--cnts[S[wstart]];
++wstart;
}
int wnd = wend - wstart + 1; // update min window
if (wnd < minw)
{
minw = wnd;
mins = wstart;
}
}
}
if (INT_MAX == minw)
return "";
else
return S.substr(mins, minw);
}
};