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.
class Solution {
public:
string minWindow(string source, string target) {
// write your code here
if(target.size()==0||source.size()==0){
return "";
}
// 1 先统计出target目标字符的个数的统计
//2 遍历 元字符串 也进行 字符统计 start end 一个符合子串的
map<char,int> mtar,msrc;
int start=0,end=-1,begin;
int found=0; // 统计发现的次数
int length=999; // 每次比较子串的长度
for(int i=0;i<target.size();++i){
mtar[target[i]]++;
}
for(int i=0;i<source.size();++i){
msrc[source[i]]++;
if(msrc[source[i]]<=mtar[source[i]]){
found++; // 发现一个目标字符就加一
}
if(found==target.size()){ //found=len 说明找到一个符合的子串
// 计算开始的位置 结尾的位置现在以i结尾
while(start<i&&msrc[source[start]]>mtar[source[start]]){
msrc[source[start]]--; // 先把start位置减一
start++; // 开始位置
}
if(i-start<length){ // 最小长度
begin=start;
end=i;
length=i-start;
}
// 将头一个字符的统计减一 往后移动
msrc[source[start]]--;
found--;
start++; //开始位置也加1;
}
}
return end==-1?"":source.substr(begin,length+1);
}
};