给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
思路:
索引对应的值存在于 T 中则加到容器里面去,若不存在则判断下一个值,同时还会判断容器中是否已经完全包含 T 中所有元素。若包含,则记录 len 和 成功的字符串的起始位置,然后在此循环内不断移动 i 指针(同时要在容器中除去此元素)寻找成功的起始位置,如果成功则再赋值,直到不成功跳出循环,寻找下一个成功的末尾位置。
代码:
class Solution {
public:
unordered_map<char, int> ori, cnt;
bool check(){
for(const auto &ret:ori){
if(cnt[ret.first] < ret.second){
return false;
}
}
return true;
}
string minWindow(string s, string t) {
for(const auto &c:t){
++ori[c];
}
int i = 0, j = -1, length = INT_MAX, ansl = -1, ansr = -1;
while(j < int(s.size())){
if(ori.find(s[++j]) != ori.end()){
++cnt[s[j]];
}
while(check() && i <= j){
if(j - i + 1 < length){
length = j - i + 1;
ansl = i;
}
if(ori.find(s[i]) != ori.end()){
--cnt[s[i]];
}
++i;
}
}
return ansl == -1?string():s.substr(ansl,length);
}
};
++ori[c];
添加元素
--cnt[s[l]];
去除元素
s.substr(ansL, len);
选取字符串
ori.find(s[++r]) != ori.end()
查找元素是否存在,若不存在则为ori,end();