题目
思路
滑动窗口+need数组,同438题
代码
string minWindow(string s, string t)
{
auto m = t.size();
auto n = s.size();
vector<int> need(123,0);
int needCnt = m;
for(const char& c:t)
{
need[c]++;
}
int R = 0, L = 0;
int stIndx = -1;
int minLen = n;
while(R<n)
{
char c = s[R];
R++;
if(need[c] > 0)
{
needCnt--;
}
need[c]--;
if(needCnt == 0)
{
while(L<R && need[s[L]] < 0)//收缩左端点,看有没有多余的元素(need[] < 0)
{
need[s[L]]++;
L++;
}
int curLen = R-L;
if(curLen <= minLen)// 需要 = ,应对 s,t俩字符串相同的情况 "ABC" "ABC",此时curLen == n
{
minLen = curLen;
stIndx = L;
}
}
}
cout << "stIndx = " << stIndx;
return stIndx == -1 ? "" : s.substr(stIndx,minLen);
}