forked from gh877916059/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path032. 最小子串覆盖.cpp
41 lines (41 loc) · 1.26 KB
/
032. 最小子串覆盖.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
class Solution {
public:
string minWindow(string &source, string &target)
{
if (source.empty() || target.empty())
return "";
int sLen = source.length(), tLen = target.length();
vector<int> sHash(256, 0), tHash(256, 0);
for (int i = 0; i < tLen; ++i)
{
++tHash[target[i]];
}
int beg = -1, end = sLen, found = 0, minLen = sLen;
for (int i = 0, start = i; i < sLen; ++i)
{
++sHash[source[i]];
if (sHash[source[i]] <= tHash[source[i]])
++found;
if (found == tLen)
{
while (start < i && sHash[source[start]] > tHash[source[start]])
{
--sHash[source[start]];
++start;
}
if (i - start < minLen)
{
minLen = i - start;
beg = start;
end = i;
}
--sHash[source[start++]];
--found;
}
}
if (beg == -1)
return "";
else
return source.substr(beg, end - beg + 1);
}
};