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.
O(n)的复杂度,以为又是动态规划什么的,可是想不到。
后来还尝试了用两个队列记录哪个字符是最左边的,新来一个比较其是否在队首,还是错了。假如中间字符要更新位置就是悲剧!
题目有个不清楚的地方没有指出如果是多个字符,也需要在s中找到多个字符?
看来还是用映射解决。
这样简单记录一个位置就是不行的,只能用queue<int>,map映射到queue<int>还是有点复杂的。
queue<int>的优点是队首一定是最左边位置。
数据结构比较复杂,网上搜别人解决方案貌似数据结构也不简单,不管了,过了,虽然时间慢
552才过大集合,这么复杂结构看来也不会快
class Solution {
public:
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(S.length()<T.length()) return "";
map<char,int> pos;
map<char,queue<int>> mapVec;
int max_num=0;
for(int i=0;i<T.length();i++)
{
map<char,int>::iterator it=pos.find(T[i]);
if(it==pos.end())
{
pos.insert(pair<char,int>(T[i],1));
}
else
{
pos[T[i]]++;
}
}
string r="";
int left_most=-1;
int find_num=0;
int minW=INT_MAX;
for(int i=0;i<S.length();i++)
{
map<char,int>::iterator it=pos.find(S[i]);
if(it==pos.end())
{
continue;
}
else
{
if(pos[S[i]]>0)
{
pos[S[i]]--;
mapVec[S[i]].push(i);
if(left_most==-1) left_most=i;
find_num++;
}
else
{
int l=mapVec[S[i]].front();
if(l==left_most) left_most=l;
mapVec[S[i]].pop();
mapVec[S[i]].push(i);
}
if(find_num==T.length())
{
int min_idx=INT_MAX;
int max_idx=i;
for(map<char,queue<int>>::iterator it=mapVec.begin();
it!=mapVec.end();it++)
{
int p=(it->second).front();
if(min_idx>p) min_idx=p;
//else if(max_idx<p) =p;
}
int w=max_idx-min_idx;
if(w<minW)
{
minW=w;
r=S.substr(min_idx,w+1);
}
}
}
}
return r;
}
};