/*该题采用的方法如下:维持一个指向S中字符的一对头尾指针s,e,这对指针指向区间的S的字符
包括T中所有的字符,然后最大程度地缩小该区间(该区间包括T中所有字符),直到最小。穷尽S中
所有的这样的最小区间,寻找到它们中的最小值,即可获得最终答案。具体步骤如下:
1.维持一对头尾指针s,e(它们初始值都为0),e不断的往后增加,直到s,e区间包含T中所有字符;
2.头指针s不断往后扫描,直到不能往后走(s,e包含的区间必须包含T中所有字符),获取此时的最小
窗口,并与之前的最小窗口比较,若为最小,则更新为最小窗口;
3.令s=s+1,重复1,2步骤。最后返回string值。
方法参考自: https://github.com/soulmachine/leetcode*/
class Solution {
public:
string minWindow(string S, string T) {
if(S.empty()) return "";
if(S.size() < T.size()) return "";
const int ascII_size = 256;
int expected_count[ascII_size] = {0};
int appeared_count[ascII_size] = {0};
for(std::size_t i = 0; i < T.size(); ++i){//获得T中每个字符的数目
++expected_count[T[i]];
}
int start(0), min_start(0);
int win_num(INT_MAX);
int total_count(0);//记录所有T中字符在S的当前区间的出现次数
for(int i = 0; i < S.size(); ++i){
if(expected_count[S[i]] > 0){
++appeared_count[S[i]];
if(appeared_count[S[i]] <= expected_count[S[i]]){
++total_count;
}
}
if(total_count == T.size()){//找到一个包含所有T中字符的window
//头指针往后走
while(expected_count[S[start]] == 0 ||
appeared_count[S[start]] > expected_count[S[start]]){
--appeared_count[S[start]];
++start;
}
//获得该当前最小区间,并与记录的区间进行比较
if(win_num > (i - start + 1)){
win_num = i - start + 1;
min_start = start;
}
--appeared_count[S[start]];
--total_count;
++start;
}
}
return win_num == INT_MAX ? "" : S.substr(min_start, win_num);
}
};
LeetCode之Minimum Window Substring
最新推荐文章于 2021-02-25 13:50:45 发布