滑动窗口
python
import collections
import sys
class Solution:
def minWindow(self, s: str, t: str):
left, right = 0, 0
n = len(s)
needs = collections.Counter(t)
window = {}
valid = 0
start = 0
length = sys.maxsize
while right < n:
c = s[right]
right += 1
if needs.get(c, -1) != -1:
if window.get(c, -1) == -1:
window[c] = 1
else:
window[c] += 1
if window[c] == needs[c]:
valid += 1
while valid == len(needs):
if right - left < length:
start = left
length = right - left
d = s[left]
left += 1
if needs.get(d, -1) != -1:
if window[d] == needs[d]:
valid -= 1
window[d] -= 1
if length == sys.maxsize:
return ''
else:
return s[start: start+length]
c++
class Solution {
public:
string minWindow(string s, string t) {
// 滑动窗口
unordered_map<char, int> needs;
unordered_map<char, int> window;
int left = 0, right = 0;
int valid = 0;
int len = INT_MAX;
int start = -1;
for (auto& c : t) {
needs[c]++;
}
int target = needs.size();
while (right < s.size()) {
// 扩大窗口
char c = s[right];
right++;
window[c]++;
if (window[c] == needs[c]) valid++;
// 缩小窗口
while (valid == target) {
if (right - left < len) {
len = right - left;
start = left;
}
char d = s[left];
left++;
if (window[d] == needs[d]) valid--;
window[d]--;
}
}
return start == -1 ? "" : s.substr(start, len);
}
};