LeetCode之Minimum Window Substring

/*该题采用的方法如下:维持一个指向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);
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值