LeetCode | 76. Minimum Window Substring多区域覆盖难题

Given a string S and a string T, find the minimum window in Swhich will contain all the characters in T in complexity O(n).

For example,
S 
"ADOBECODEBANC"
T 
"ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return theempty string 
"".

If there are multiple such windows, you are guaranteed thatthere will always be only one unique minimum window in S.

这题的解决方法和leetcode  632. Smallest Range的解决方法一模一样,在我的博客里面也有632的解题报告,这里不仔细叙述

要说一下的是这一题的陷阱贼多,首先题目说的是string S和string T,这两个都是字符串,字符串意味着可能包含任何字符,因此S和T都有可能包含任何字符,以后在做题的时候要记住,如果题目没有特别说明,任何string都该认为是包含任何字符

然后题目说的是Scontan all the characters 实际上是S covers all characters in T ,在T里面重复的字符也算的,这一点是这一题没说清楚,以后在做题的时候一定要记住cover和contain的区别,一个是每种字符包含一个,一种是每种字符包含的个数要多于一定的值

要记住,isupper可以用来判断字符是否是大写字母,islower可以用来判断字母是否是小写字母!

class Solution {
public:
   int getNum(char a)
{
	if (islower(a))
	{
		return a - 'a';
	}
	if (isupper(a))
	{
		return a - 'A'+26;
	}
	return 52;
}
string minWindow(string s, string t) {
	int count[52] = { 0 };
	int mark[53] = { 0 };
	int theAllG = 0;
	int l;
		for (int j = 0; j < t.size(); j++)
		{
			l = getNum(t[j]);
			if (l != 52) { if (mark[l] == 0) theAllG++; mark[l]++; }
		}

	int left, right,k;
	int n = s.size();
	left = 0; right = 0; k = 0;
	string result=""; int theMinLength=INT_MAX;
	while (right != n)
	{
		l = getNum(s[right]);
		if (mark[l]>0)
		{
			count[l]++;
			if (count[l] == mark[l])
			{
				k++;
			}
		}
		if (k == theAllG)
	   {
			while (k == theAllG)
			{
				l = getNum(s[left]);
				if (mark[l]>0)
				{
					count[l]--;
					if (count[l] < mark[l])
					{
						k--;
					}
				}
				left++;
		   }
			
			if (right - left+2 < theMinLength)
			{
				theMinLength = right - left + 2;
				result = s.substr(left - 1, right - left + 2);
			}
	   }
		right++;
	}
	return result;
}
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值