给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的子串。
样例
给出source = "ADOBECODEBANC",target ="ABC" 满足要求的解 "BANC"
注意
如果在source中没有这样的子串,返回"",如果有多个这样的子串,返回起始位置最小的子串。
挑战 要求时间复杂度为O(n)
class Solution {
public:
bool cmp(map<char,int> &s,map<char,int> &t){//确保s中每个字符出现次数不小于t中相同字符
for(auto e:t){ //出现的次数,实现覆盖
if(s[e.first]<e.second)
return false;
}
return true;
}
string minWindow(string &source, string &target) {
map<char,int> mark ;
map<char,int> check; //check记录source中出现的字符的次数(这些字符也在target中出现)
for(auto e:target)
++mark[e];
int begin=0,end=0,n=source.length();
int min=INT_MAX;
string ret;
while(end<n){
if(mark.count(source[end])!=0)
++check[source[end]]; //如果也在target中出现了,就记录下来
while(cmp(check,mark)){
if(end-begin+1<min){ //保存记录最小值
min=end-begin+1;
ret=source.substr(begin,end-begin+1);
}
--check[source[begin]]; //begin要向前移动一位,所以begin本来指向的字符的个数要减减
++begin; //begin前移
}
++end;
}
return min==INT_MAX?"":ret;
}
};