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;
}
};