76. Minimum Window Substring
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.
Sliding window [left, right]
技巧:
用hash table来存target string里每个字符出现的次数。
用count来数sliding window里包含的满足要求的字符的个数:
1. 当检查right pointer的时候,如果hash table里该字符的hash value >0,说明,这个字符满足要求(该字符出现在t里面,并且未达到t里该字符出现的次数), count 加一;如果该字符的hash value<=0, 说明 1)该字符没有出现在t里面,或者2)出现在t里面,可是sliding window里该字符出现的次数已经满足,现在的是多余的。然后更新hash table里该字符的hash value: 减一。
2. 当检查left pointer的时候,首先更新hash table里该字符的hash value:加一。如果该字符更新后的hash value>0,说明,该字符是符合条件的字符,当移动left point(将该字符从sliding window里去除),count减一。
1 class Solution { 2 public: 3 string minWindow(string s, string t) { 4 string result; 5 if(s.size()<t.size()){ 6 return result; 7 } 8 unordered_map<char,int> freq; 9 //hash table to count frequency for each letter 10 for(char c: t){ 11 freq[c]++; 12 } 13 14 int left=0; 15 int count=0; 16 int length = INT_MAX; 17 18 //sliding window [left, i] 19 for(int i=0;i<s.size();i++){ //move right pointer 20 if(freq[s[i]]-->0){ //s[i], current letter is in T 21 count++; 22 } 23 while(count==t.size()){ //sliding window meet the requirement (contains all charaters from T) 24 if(i-left+1<length){ 25 length = i -left+1; 26 result=s.substr(left,length); 27 } 28 29 if(++freq[s[left]]>0){ //s[left], current letter is in T 30 count--; 31 } 32 33 left++; //move left pointer 34 } 35 } 36 37 return result; 38 } 39 }; 40 //The question is how to easily check whether the slicing window contains all characters in T?