class Solution {
public:
string minWindow(string s, string t) {
if(t.empty()||s.empty()||s.size() < t.size())
return "";
int p1 = 0, p2 = 0;
int count = t.size();
int limit = s.size();
int pos = -1, length = limit + 1;
map<char, int> mapCount;
for(auto i : t) //记录T中每个 char 出现的次数
mapCount[i]++;
while(p2 < limit){
if (mapCount[s[p2]] > 0)
--count;
--mapCount[s[p2]]; //减少所需要T中字符串的个数
++p2;
// p2 移到包含所有 t 的位置,p1开始 缩减
while (count == 0){
if (p2 - p1 < length){
length = p2 - p1;
pos = p1;
}
if (mapCount[s[p1]] == 0) ++count; //说明当前串已经包含所有 S[p2]字符
++mapCount[s[p1]];//增加所需要T中字符串的个数
++p1;
}
}
if(pos < 0) return "";
return s.substr(pos,length);
}
};
Minimum Window Substring
最新推荐文章于 2021-07-25 04:26:46 发布