【leetcode】Minimum Window Substring (hard) ★
2015-03-10 22:38
447 查看
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 =
T =
Minimum window is
Note:
If there is no such window in S that covers all characters in T, return the emtpy string
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
思路:题目中T可能会有重复的字母 我用了各种分类讨论 结果超时
直接看大神的代码吧
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 emtpy string
"".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
思路:题目中T可能会有重复的字母 我用了各种分类讨论 结果超时
直接看大神的代码吧
class Solution { public: string minWindow(string S, string T) { int m = S.size(), n = T.size(); if (n <= 0 || m < n) return ""; int require[128] = {0}; //记录每种字母需要多少个 关键点 for (int i = 0; i < n; ++i) require[T[i]]++; int count = 0; int minLen = INT_MAX, minIndex = 0; for (int s = 0, e = 0; e < m; ++e) { require[S[e]]--; //末尾数字的需求量减1 if (require[S[e]] >= 0) count++; //如果需求量大于等于0 说明匹配上了新的数字 while (count == n) { //所有字母都被匹配上了 if (e - s + 1 < minLen) { //长度变小了 记录下新的长度 和 起始位置 minLen = e - s + 1; minIndex = s; } require[S[s]]++; //起始位置向后移更新需求量 if (require[S[s]] > 0) count--; s++; } } if (minLen == INT_MAX) return ""; return S.substr(minIndex, minLen); } };
相关文章推荐
- leetcode hard模式专杀之76 Minimum Window Substring
- 【LeetCode练习题】Minimum Window Substring
- LeetCode(76) Minimum Window Substring
- leetcode[76]Minimum Window Substring
- LeetCode--Minimum Window Substring(最小匹配子串)
- LeetCode 76 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
- [LeetCode]Minimum Window Substring
- Leetcode-76 Minimum Window Substring
- LeetCode76 Minimum Window Substring(两种解法)
- leetcode Minimum Window Substring
- LeetCode Minimum Window Substring
- leetcode 76 Minimum Window Substring/ 209 Minimum Size Subarray Sum
- LeetCode--Minimum Window Substring