同时请参阅 :http://blog.youkuaiyun.com/martin_liang/article/details/8592894
相同的问题,解法稍微有一点不一样
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.
class Solution {
public:
string minWindow(string S, string T) {
map<char, int> matchingMap;
for (int i=0; i<T.size(); i++)
{
if (matchingMap.find(T.at(i)) == matchingMap.end())
{
matchingMap[T.at(i)] = 1;
}
else
{
matchingMap[T.at(i)]++;
}
}
map<char, int> loopingMap;
int count = 0;
int startPos = 0;
int minLen = S.size();
string retString;
for (int i=0; i<S.size(); i++)
{
if (matchingMap.find(S.at(i)) != matchingMap.end())
{
if (loopingMap.find(S.at(i)) == loopingMap.end())
{
loopingMap[S.at(i)] = 1;
}
else
{
loopingMap[S.at(i)]++;
}
if (loopingMap[S.at(i)] <= matchingMap[S.at(i)])
count++; // example T:ABC S: AAABC, 当遇到第二和第三个A时,count都不会加一,最终要进行match的时候,count必定为3
if (count == T.size())
{
while (true) // 注意这里的循环
{
if (matchingMap.find(S.at(startPos)) == matchingMap.end())
{
startPos++;
continue;
}
if (loopingMap[S.at(startPos)] > matchingMap[S.at(startPos)])
{
loopingMap[S.at(startPos)]--;
startPos++;
}
else
{
break;
}
}
if (i-startPos+1 <= minLen)
{
minLen = i-startPos+1;
retString = S.substr(startPos, minLen);
}
count--;
loopingMap[S.at(startPos)]--;
startPos++;
}
}
}
return retString;
}
};