LeetCode--Minimum Window Substring
2017-10-11 10:44
375 查看
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.
思路:哈希表法。这里用两个数组tm和sm代替哈希表,首先统计T中每个字母的个数(可能一个字母有多个),然后开始滑动窗口,左端点起点为0,遍历右端点,如果遇到S中有T中的字母且个数不超过T中该字母的个数,则计数加1,直到计数达到T中字母个数,即S中窗口包含T为止,如果该窗口小于最小窗口长度,则更新最小窗口,同时左端点前移,如果左端点包含T中字母,则减去一个S中该字母的个数,若此时所需T中该字母个数不够,则计数减1,继续前移右窗口,滑动窗口直到结束。
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.
思路:哈希表法。这里用两个数组tm和sm代替哈希表,首先统计T中每个字母的个数(可能一个字母有多个),然后开始滑动窗口,左端点起点为0,遍历右端点,如果遇到S中有T中的字母且个数不超过T中该字母的个数,则计数加1,直到计数达到T中字母个数,即S中窗口包含T为止,如果该窗口小于最小窗口长度,则更新最小窗口,同时左端点前移,如果左端点包含T中字母,则减去一个S中该字母的个数,若此时所需T中该字母个数不够,则计数减1,继续前移右窗口,滑动窗口直到结束。
class Solution { public: string minWindow(string S, string T) { if (T.size()>S.size()) return ""; string res=""; int left=0,count=0,minLen=S.size()+1; int tm[256]={0},sm[256]={0}; for(int i=0;i<T.size();i++) tm[T[i]]++; for(int right=0;right<S.size();right++){ if(tm[S[right]]){ sm[S[right]]++; if(sm[S[right]]<=tm[S[right]]) count++; while(count==T.size()){ if(right-left+1<minLen){ minLen=right-left+1; res=S.substr(left,minLen); } if(tm[S[left]]){ sm[S[left]]--; if(sm[S[left]]<tm[S[left]]) count--; } left++; } } } return res; } };
相关文章推荐
- 【LeetCode练习题】Minimum Window Substring
- [LeetCode] Minimum Window Substring 解题报告
- LeetCode OJ Minimum Window Substring
- LeetCode Minimum Window Substring
- LeetCode - Minimum Window Substring
- LeetCode 76 Minimum Window Substring
- LeetCode题解——Minimum Window Substring
- [LeetCode][Java] Minimum Window Substring
- Leetcode---Minimum Window Substring
- [leetcode]Minimum Window Substring
- LeetCode解题报告—— Minimum Window Substring && Largest Rectangle in Histogram
- leetcode 67.Minimum Window Substring
- [LeetCode] Minimum Window Substring
- [LeetCode] Minimum Window Substring
- leetcode minimum window subString
- Leetcode-Minimum Window Substring
- [Leetcode] Minimum Window Substring My Submissions Question Solution
- LeetCode - Minimum Window Substring 题解
- [LeetCode P76] Minimum Window Substring
- [Leetcode] Minimum Window Substring