问题描述:
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).
Example:
Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC"
Note:
- If there is no such window in S that covers all characters in T, return the empty string
""
. - If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
题目意思就是找到S最小的字串,该字串包含了T中所有的字符(不一定按顺序)
解题思路:
该题就要使用到Hash表(其实比较占空间,不得以的时候不建议使用)。
- 首先将T中的字符存在hash中,用num表示T的长度,用left表示字串左端的位置;
- 开始遍历S,若该字符s[i]在hash中,则num--,hash[s[i]]--,在进入第3步,否则直接进入第3步;
- 若num==0,则表示判断此时字串的长度是否比之前小,小则替换,start=left,进入第4步;若num!=0,直接进入第5步;
- 若hash[s[left]]==0,则left++,num++;否则返回第3步;
- 返回第2步;
- 取出字符串。
思路分析:就是找到一个字串包含T后,不断的将左边去掉,直到不包含。然后再向右边扩展。
源码:
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> hash;
for(auto v : t) hash[v]++;
int N = s.length(), start=0, left=0, res = INT_MAX, num = t.length();
for(int i=0; i<N; i++){
if(hash[s[i]]-- > 0) num--;
while(num == 0){
res = res < i-left+1? res: i-(start=left)+1;
if(hash[s[left++]]++ == 0) num++;
}
}
return res == INT_MAX ? "" : s.substr(start, res);
}
};