76. Minimum Window Substring
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.
Approach
题目大意:找到长度最小的序列并且包含T中所有的字母
解题思路:用的还是滑动窗口的思想,关键主要是能找到一个标志用来判断窗口是否满足要求,然后进行滑动。所以窗口滑动的标志就是这个窗口已包含了t中的所有字母,然后就可以滑动了。
Code
class Solution {
public:
string minWindow(string s, string t) {
vector<int> expects(256, 0), apper(256, 0);
for (const char &st:t)expects[st]++;
int left = 0, width = 0, cnt = 0, mleft = 0;
for (int right = 0; right < s.size(); right++) {
if (expects[s[right]]) {
apper[s[right]]++;
if (apper[s[right]] <= expects[s[right]]) {
++cnt;
}
}
if (cnt == t.size()) {
while (expects[s[left]] == 0 || apper[s[left]] > expects[s[left]]) {
apper[s[left]]--;
left++;
}
if (width == 0 || width > right - left + 1) {
width = right - left + 1;
mleft = left;
}
}
}
if (width == 0)return "";
return s.substr(mleft, width);
}
};