给定一个字符串 S 和一个字符串 T,请在 S 中找出包含 T 所有字母的最小子串。
示例:
输入: S = “ADOBECODEBANC”, T = “ABC”
输出: “BANC”
说明:
如果 S 中不存这样的子串,则返回空字符串 “”。
如果 S 中存在这样的子串,我们保证它是唯一的答案。
class Solution {
public:
string minWindow(string s, string t) {
if(s.length() == 0 || t.length() == 0 || s.length() < t.length())
return "";
string strRes = "";
int sLen = s.length(), tLen = t.length();
int start = 0; //字符串起始索引
int left = 0, right = 0; //左滑窗索引和右滑窗索引
int count = 0; //计数器
int minLen = INT_MAX;
map<char, int> mapT;
for(int i = 0; i < tLen; i++)
{
if(mapT.find(t[i]) == mapT.end())
{
mapT[t[i]] = 1;
}
else
{
mapT[t[i]]++;
}
}
while(left < sLen)
{
if(count < tLen)
{
if(right >= sLen) break;
if(mapT.find(s[right]) != mapT.end())
{
mapT[s[right]]--;
if(mapT[s[right]] >= 0) //剔除重复项,注意此处是先减减再判断,这样可剔除多个同样的重复项
{
count++;
}
}
right++;
}
else if(count == tLen) //匹配到存在的子串,内部滑窗
{
if(minLen > right - left)
{
minLen = right - left; //注意此处的距离是right-left,前面已经有了right++
//下一次遍历的时候指向了已匹配字符的下一个字符
start = left;
}
left++;
if(mapT.find(s[left-1]) != mapT.end())
{
++mapT[s[left-1]];
if(mapT[s[left-1]] > 0) //剔除重复项,注意此处是大于0
{
count--;
}
}
}
else
{
}
}
if(minLen != INT_MAX)
{
strRes = s.substr(start, minLen);
}
return strRes;
}
};