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
思路:滑动窗口,包含子串(顺序任意)的最小窗口,先把子串转为map来表示,然后用两指针,start和j,每次只要窗口内子串数不为0就递增j,每次遍历都把map计数器--,只有>=0说明该元素是子串中的(不是重复的)把m--(这里用m是否为0来更新ans,0说明窗口已经包含了子串),m=0递增start并map对start的计数++,>0说明一定是子串中(不重复)只有重复或不是子串的才会=0或者小于0,根据这两条来移动指针。
class Solution {
public:
string minWindow(string s, string t) {
int n=s.size(),m=t.size();
vector<int> h(130);
for(auto c:t) h[c]++;
int i=0,start=0,len=INT_MAX,cur=0;
while(i<=n&&start<n){
if(m){
if(i==n) break;
h[s[i]]--;
if(h[s[i]]>=0) m--;
i++;
}else{
if(len>i-start){
len=i-start;cur=start;
}
h[s[start]]++;
if(h[s[start]]>0) m++;
start++;
}
}
return len==INT_MAX?"":s.substr(cur,len);
}
};