代码

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
class Solution {
public:
string minWindow(string s, string t) {
string res = "";
int m[128] = { 0 }; //哈希数组
int left = 0, right = 0, need = t.size(), minstart = 0, minlen = INT_MAX;
for(char c : t)
++m[c]; //记录t中字符出现次数
while(right < s.size())
{
if(m[s[right]] > 0) --need; //窗口右移,每包含一个t中的字符,need--
--m[s[right]];
++right;
while(need == 0) //当t中的字符全部被包含在[left,right]时
{
if(right - left < minlen)
{
minstart = left;
minlen = right - left;
}
++m[s[left]]; //窗口左移
if(m[s[left]] > 0) ++need;
++left;
}
}
if(minlen != INT_MAX) res = s.substr(minstart , minlen);
return res;
}
};