class Solution {
public:
string minWindow(string s, string t) {
int slen=s.length();
int tlen=t.length();
int need[128]={INT_MIN};
for(int i=0;i<tlen;i++)
need[t[i]]=need[t[i]]==INT_MIN?1:need[t[i]]+1;
int start=0,end=0,count=0,min_len=INT_MAX,min_idx=0;
for(;end<slen;end++)
{
if(need[s[end]]>0)//needed by t
{
need[s[end]]--;
count++;
}
else if(need[s[end]]!=INT_MIN)needed but the number is enough
need[s[end]]--;
if(count==tlen)
{
while(need[s[start]]<0)//find the non-redundant start
{
if(need[s[start]]!=INT_MIN)
++need[s[start++]];
else
start++;
}
if(end-start+1<min_len)//update the min
{
min_len=end-start+1;
min_idx=start;
}
need[s[start]]++;
start++;
count--;
}
}
return min_len==INT_MAX?"":s.substr(min_idx,min_len);
}
};
leetcode 76: Minimum Window Substring
最新推荐文章于 2020-04-23 13:11:31 发布