/*********************************************************************
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.
/***********************************************************************
思路:
1,用 双指针法,两个指针夹的子字符串就是 Minimum window。【在字符串或数组中扣出指定的子字符串或子数组常常用这种思想】
2,用一个map来储存字符和出现次数的关系,map<char,int>。
3,初始化map时,用T中字符出现的字符次数来初始化,如:T="aabc",则 map[a]=2,map[b]=1,map[c]=1;
4,遍历 S, S中字符x每出现一次,map[x]--;用 count 来统计T在S中还需出现的数目。初始化 count=t.size();
每出现一次T中字符 count--;当count==0时表示S出现完了T中字符。
/**********************************************************************
代码:
class Solution{
public:
string minWindow(string s, string t){
map<char, int> map; //(128, 0);
for (auto c : t) map[c]++;
int count = t.size(), begin = 0, end = 0, head = 0,d=INT_MAX;
while (end < s.size()){
if (map[s[end++]]-->0) count--;
while (count == 0){
if (d > (end - begin)){
d = end - begin;
head = begin;
}
if (map[s[begin++]]++ == 0) count++; // 为什么是 map[s[begin]]++ ??因为往后移动了就还缺一个 s[begin].
}
}
return d == INT_MAX ? "" : s.substr(head,d);
}
};