class Solution {
private:
bool coverall(unordered_map<char,int> smap,string t){
for(int j=0;j<t.size();j++){
auto found=smap.find(t[j]);
if(found==smap.end()){
return false;
}
else{
--found->second;
if(found->second==0)
{
smap.erase(found);
}
}
}
return true;
}
public:
string minWindow(string s, string t) {
unordered_map<char,int> smap;
int start=0;
int minstart;
int ans=INT_MAX;
string subs;
for(int end=0;end<s.size();end++){
smap[s[end]]++;
//cout<<"start:"<<start<<"end:"<<end<<"smap[s[end]]:"<<smap[s[end]]<<endl;
while(end-start+1>=t.size() && coverall(smap,t)){
//cout<<"start:"<<start<<"end:"<<end<<"end-start+1:"<<end-start+1<<endl;
if(ans>end-start+1){
ans=end-start+1;
//cout<<"start:"<<start<<"end:"<<end<<"ans:"<<ans<<endl;
subs=s.substr(start,end-start+1);
}
auto found=smap.find(s[start]);
smap[s[start]]--;
//cout<<"start:"<<start<<"smap[s[start]]:"<<smap[s[start]]<<endl;
if(smap[s[start]]==0){
smap.erase(found);
}
start++;
}
}
return subs;
}
};
由上一道接水果的题知道了用哈希表记录出现的种类和数量。
这道题的实质是要求s字串的种类和数量必须大于等于t的种类和数量
这道题自己写出来了,但是超时,下面是简化版:
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char,int> smap;
unordered_map<char,int> tmap;
for(int i=0;i<t.size();i++){
tmap[t[i]]++;
}
int start=0;
int cnt=0;
string subs;
for(int end=0;end<s.size();end++){
smap[s[end]]++;
if(smap[s[end]]<=tmap[s[end]]){
cnt++;
}
while(smap[s[start]]>tmap[s[start]]){
smap[s[start++]]--;
}
if(cnt==t.size()){
if(subs.empty() || end-start+1 < subs.size()){
subs=s.substr(start,end-start+1);
}
}
//cout<<"start:"<<start<<"end:"<<end<<"smap[s[end]]:"<<smap[s[end]]<<endl;
}
return subs;
}
};