Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
题解:
滑动窗口,首先计算出t中所有字符出现次数,用map存储,然后遍历s,当遍历到符合要求时,保存当前left,rigth和长度,即t中所有字符都出现了,左边开始收缩窗口,收缩到t中所有字符不出现,即不满足要求,然后再往下遍历s寻找下一个符合要求的串。
class Solution {
public:
string minWindow(string s, string t) {
int n = s.length(), num = t.length();
unordered_map<char, int> mp;
for (int i = 0; i < num; i++) {
mp[t[i]]++;
}
int len = n + 1, appear = 0, left = 0, begin = 0;
for (int i = 0; i < n; i++) {
if (mp.find(s[i]) != mp.end()) {
mp[s[i]]--;
if (mp[s[i]] >= 0) {
appear++;
}
}
while (appear == num) {
if (i - left + 1 < len) {
begin = left;
len = i - left + 1;
}
if (mp.find(s[left]) != mp.end()) {
mp[s[left]]++;
if (mp[s[left]] > 0) {
appear--;
}
}
left++;
}
}
if (len == n + 1) {
return "";
}
return s.substr(begin, len);
}
};