-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathMinimumWindowSubstring.cpp
48 lines (41 loc) · 1.08 KB
/
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
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
string minWindow(string S, string T) {
if (S.length() < T.length() || T.empty()) return "";
const int MAX_CHAR_CNT = 256;
int hasFound[MAX_CHAR_CNT];
int needToFind[MAX_CHAR_CNT];
memset(hasFound, 0, sizeof(hasFound));
memset(needToFind, 0, sizeof(needToFind));
for (size_t i = 0; i < T.length(); ++i) {
needToFind[(int)T[i]]++;
}
int minBeg = 0;
int minLen = INT_MAX;
int bPos = 0;
int totalFound = 0;
for (int e = 0; e < S.length(); ++e) {
if (!needToFind[(int)S[e]]) continue;
hasFound[(int)S[e]]++;
if (hasFound[(int)S[e]] <= needToFind[(int)S[e]]) {
totalFound++;
}
if (totalFound == T.length()) {
while (bPos < e) {
if (needToFind[(int)S[bPos]]) {
if (hasFound[(int)S[bPos]] - 1 >= needToFind[(int)S[bPos]]) {
hasFound[(int)S[bPos]]--;
} else break;
}
++bPos;
}
if (minLen > e - bPos + 1) {
minLen = e - bPos + 1;
minBeg = bPos;
}
}
}
if (totalFound != T.length()) return "";
return string(S, minBeg, minLen);
}
};