Minimum Window Substring--LeetCode
2017-10-21 15:05
465 查看
1.题目
Minimum Window SubstringGiven 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.
2.题意
找出s中能包含t的最小窗口3.分析
遍历t,在m中记录t中各个字符出现的次数遍历s,更改s中各个字符在m中出现的次数
当子串包含t时,尝试将左边界右移,从而缩小窗口
注意判断left与right时不要写反
还有while循环里面++left一定不要遗漏
4.代码
class Solution { public: string minWindow(string s, string t) { string result; if(s.size() < t.size()) return result; unordered_map<char, int> m; for(int i = 0; i < t.size(); ++i) { if(m.find(t[i]) != m.end()) ++m[t[i]]; else m[t[i]] = 1; } int left = 0; int count = 0; int minLen = s.size() + 1; for (int right = 0; right < s.size(); ++right) { if(m.find(s[right]) != m.end()) { --m[s[right]]; if(m[s[right]] >= 0) ++count; while(count == t.size()) { if(right - left + 1 < minLen) { minLen = right - left + 1; result = s.substr(left, minLen); } if(m.find(s[left]) != m.end()) { ++m[s[left]]; if(m[s[left]] > 0) --count; } ++left; } } } return result; } };
相关文章推荐
- 【leetcode】Minimum Window Substring
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- 【LeetCode】Minimum Window Substring
- LeetCode_OJ【76】Minimum Window Substring
- Leetcode Minimum Window Substring
- LeetCode76 Minimum Window Substring
- LeetCode()Minimum Window Substring 超时,但觉得很清晰。
- leetcode: Minimum Window Substring
- [LeetCode] Minimum Window Substring 最小窗口子串
- (细节题)[LeetCode]Minimum Window Substring
- leetcode - Minimum Window Substring
- LeetCode-Minimum Window Substring -- 窗口问题
- LeetCode Minimum Window Substring
- Minimum Window Substring -- LeetCode
- [LeetCode] Minimum Window Substring
- LeetCode(76) Minimum Window Substring
- LEETCODE: Minimum Window Substring
- [Leetcode] minimum window substring 最小字符窗口
- leetcode -- Minimum Window Substring
- [leetcode-76]Minimum Window Substring(java)