Given a string S and a string T, find the minimum window in S which 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 the empty string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Solution
哈希表
Code
// 9 ms AC
class Solution {
public:
string minWindow(string s, string t)
{
vector<int> HashMap(128, 0); //初始化一个哈希表
int begin = 0, end = 0, head = 0; //head和 end 记录最后的头尾
int lent = t.length(), lens = s.length();
int Count = lent, MinLen = INT_MAX; //Count用于统计是否是有效子串
//初始化哈希表
for(int i=0;i<lent;i++)
HashMap[t[i]]++;
while(end < lens)
{
if(HashMap[s[end++]]-- > 0) //在T中,计数减一
Count--;
while(Count == 0) //是符合要求的子串
{
if(MinLen > (end-begin))
{
MinLen = end-begin;
head = begin;
}
if(HashMap[s[begin++]]++ == 0) //现在等于0,说明之前存在于T中。否则在第一个if的时候,HashMap的值就变成负的了
Count++;
}
}
if(MinLen == INT_MAX)
return "";
else
return s.substr(head, MinLen);
}
};

278

被折叠的 条评论
为什么被折叠?



