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 empty string ""
.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
class Solution {
public:
string minWindow(string S, string T) {
int data[260],i,j;
memset(data,0,sizeof(data)); //给data数组分配内存空间。
for(i=0;i<T.length();++i)
data[T[i]]++; //data里面的内容是T的内容 作为目标字符串
int now[260],left,right,minn=INT_MAX,num=0;
memset(now,0,sizeof(now)); //给now数组分配内存空间
for(i=0,j=0;i<S.length();++i)
{
if(num<T.length()) //
{
if(now[S[i]]<data[S[i]])
num++;
now[S[i]]++;
}
if(num==T.length()) //如果num已经达到了数目 说明已经找到了一个
{
while(j<=i&&now[S[j]] - 1 >= data[S[j]]) //此处主要是为了找到第一个符合的元素 真是用心良苦
{
--now[S[j]]; //now值都做减一操作 因为如果是AAAA 那么肯定要后移 即便是不同的CDE也得是需要后移的因为CDE的data的值是1
++j;
}
if(minn>i-j+1)
left=j,right=i,minn=i-j+1; //处理最小窗口大小比对
while(j<=i&&num==T.length()) //找到前面第一个在T中的元素 此时j就是新的起点 同时num减一了
{
now[S[j]]--;
if(now[S[j]]<data[S[j]])
num--;
++j;
}
}
}
string temp;
if(minn<INT_MAX)
return temp.assign(S,left,right-left+1);
else
return "";
}
};