// 双指针, 哈希表
class Solution {
public:
string minWindow(string s, string t) {
vector<int> cnt(128, 0);
for (int e : t) { cnt[e]++; }
int begin, minWindowLen = INT_MAX;
int tLen = t.size();
for (int tail = 0, head = 0; head < s.size();) {// [tail, head)
//统计t中还剩多少没有字符被覆盖掉
if (cnt[s[head++]]-- > 0) { tLen--; }
// t被s中[tail... head)(开区间)位置的子串覆盖
if (tLen == 0) {
// 更新tail, 将从tail开始的一段字串剔除,因为重复覆盖了
while (cnt[s[tail]] < 0) { cnt[s[tail++]]++; }
if (minWindowLen > head - tail) {
minWindowLen = head - tail;
begin = tail;
}
// 移动tail,使得覆盖失效
cnt[s[tail++]]++;
tLen++;
}
}
return minWindowLen == INT_MAX ? "" : s.substr(begin, minWindowLen);
}
};
leetcode 67.Minimum Window Substring
最新推荐文章于 2020-04-23 13:11:31 发布