class Solution {
public:
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
* Return "" if there is no such a string
*/
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);
}
};
// 1 遍历 目标字符串进行统计
// 2 遍历源字符串 ,进行统计 found 个数 。 判断 start end 位置 计算length
map<char,int> msrc,mtar;
int start=0,len=999;
int found=0; // 源字符串中目标字符串个数
int begin=0,end=-1;;
for(int i=0;i<t.size();++i){
mtar[t[i]]++;
}
for(int i=0;i<s.size();++i){
msrc[s[i]]++;
if(msrc[s[i]]<=mtar[s[i]]){
found++;
}
if(found==t.size()){
// 找到开始位置
while(start<i&&msrc[s[start]]>mtar[s[start]]){
msrc[s[start]]--;
start++;
}
if(len>(i-start)){
begin=start;
end=i;
len=i-start;
}
// 头一个减1
msrc[s[start]]--;
found--;
start++;
}
}
return end==-1?"":s.substr(begin,len+1);
包含字符串t最小窗口子字符串
猜你喜欢
转载自blog.csdn.net/u010325193/article/details/86516931
今日推荐
周排行