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.
思路:采用双指针记录窗口的左右边界,通过数组记录窗口字符和非窗口字符的数量是否大于或小于0,判断移动双指针策略。
class Solution {
public:
string minWindow(string s, string t) {
int count[128]={0};
for(auto i : t) count[i]++; //记录窗口各字符数量
int strlen=0,minlen=s.size();
string res;
for(int l=0,r=0; r< s.size(); r++){
//若是窗口字符 +1,否则-1
if(--count[s[r]] >= 0 ) strlen++; //每匹配一个窗口字符,记录一下
while(strlen == t.size()){ //窗口字符全部匹配成功,定位窗口位置
if(minlen >= (r-l+1)){
minlen = r-l+1;
res = s.substr(l,minlen);
}
if(++count[s[l++]] >0) strlen--; //抛弃一个窗口字符,则匹配长度-1,不是窗口字符不受影响
}
}
return res;
}
};