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).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
最小窗口子串,已知字符串S和字符串T,求在S中的最小窗口(区间),使得这个区间中包含字符串T中的所有字符。
解法:采用哈希表记录出现的字符,用双指针界定窗口,寻找包含字符串T中的所有字符的最小窗口。
class Solution {
private:
bool isContain(vector<int> map_cur_s, vector<int> map_t)
{
int len = map_cur_s.size();
for (int i = 0; i < len; i++)
{
if (map_cur_s[i] < map_t[i])
return false;
}
return true;
}
public:
string minWindow(string s, string t) {
if (s.size() < t.size())
return "";
vector<int> map_t(128,0);
set<char> log_t;
for (int i = 0; i < t.size(); i++)
{
map_t[t[i]]++;
log_t.insert(t[i]);
}
int begin = 0, i = 0;
string result;
int minLen = INT_MAX;
vector<int> map_cur_s(128, 0);
while (i <= s.size())
{
map_cur_s[s[i]]++;
while (begin <= i)
{
if (log_t.find(s[begin]) == log_t.end() || map_cur_s[s[begin]] > map_t[s[begin]])
{
map_cur_s[s[begin]]--;
begin++;
}
else
{
break;
}
}
int count = i - begin + 1;
if (isContain(map_cur_s, map_t))
{
if (count < minLen)
{
minLen = count;
result = s.substr(begin, count);
}
}
i++;
}
return result;
}
};