
此题一看就是滑动窗口,其实算不上太hard,有两个难点:
- judge函数的写法,如何判断候选集合包含模板集合?
- 如何存目标子串
对于第一个问题,我们可以用一个128维的数组,因为字母,数字都是ascii码,所以这样最简单最快。如果用哈希表或者树就慢了,特别是树,同一个字符要遍历好多次,才能拿到值
对于第二个问题,我们如果每次都用substr,会每次存都是一个O(N)的复杂度,就超时了,所以存一个左坐标,一个右坐标就行,代码如下:
cpp
typedef vector<int> V;
class Solution {
public:
bool judge(V& t, V& temp)
{
for(int i='a';i<='z';i++)
{
if(t[i] < temp[i])return 0;
}
for(int i='A';i<='Z';i++)
{
if(t[i] < temp[i])return 0;
}
return 1;
}
string minWindow(string s, string t) {
// 预处理t
V temp(128, 0), cand(128, 0);
for(auto c: t)temp[c]++;
int m = s.size();
int ans_l = -1, ans_r = m;
int l = 0;
for(int r=0;r<m;r++)
{
int c = s[r];
cand[c]++;
while(judge(cand, temp))
{
if(r-l < ans_r-ans_l)
{
ans_l = l;
ans_r = r;
}
cand[s[l]]--;
l++;
}
}
if(ans_l < 0)return "";
return s.substr(ans_l, ans_r-ans_l+1);
}
};