Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC"
.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
采用双指针,end指针逐渐增加,当begin与end之间包含所有t后,后移begin,找到最小substr,并记录,最后输出最小substr。边界条件,begin处的字母属于t且在该区域中仅出现t中的次数。
class Solution {
public:
string minWindow(string s, string t) {
int slen=s.size();
int tlen=t.size();
if(tlen==||slen<tlen) return "";
int needfind[]={};
int hasfind[]={};
for(int i=;i<tlen;i++)
{
needfind[t[i]]++;
}
int count=;
int begin=;
int end=;
int minwindowsizetmp=;
int minbegin=;
int minend=slen-;
int minwindowsize=INT_MAX;
for(count=;end<slen;end++)
{
if(needfind[s[end]]==)
continue;
hasfind[s[end]]++;
if(hasfind[s[end]]<=needfind[s[end]])
{ count++;
} if(count==tlen)
{
while(begin<end)
{
if(needfind[s[begin]]==)
{
begin++;
continue;
}
if(hasfind[s[begin]]>needfind[s[begin]])
{
hasfind[s[begin]]--;//若该行放到begin++下边,则会出现下述错误,谨记。
begin++; continue;
}
else
break;
}
minwindowsizetmp=end-begin+; if(minwindowsizetmp<minwindowsize)
{
minbegin=begin;
minend=end;
minwindowsize=minwindowsizetmp;
}
}
}
if(minwindowsize==INT_MAX)
return "";
return s.substr(minbegin,minwindowsize);
}
};
wrong answer:
Input:"ADOBECODEBANC", "ABC"
Output:"ANC"
Expected:"BANC"