LeetCode[Hash Table]: Minimum Window Substring
2015-02-04 20:58
351 查看
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.
对于这个题目,我毫无头绪,当我在Discuss上看懂这个解法的时候:https://oj.leetcode.com/discuss/10337/accepted-o-n-solution我觉得这个解法实在是太妙了!这个链接有关于这个解法的idea:https://oj.leetcode.com/discuss/5469/is-the-length-of-t-considered-constant-or-m
下面先贴出这个解法的代码:
直观地理解这个算法是比较困难的,建议用一些例子跑起来,这样会比较容易理解这个算法为什么能到期望的目的。总之我很为这个解法而惊叹!
这个算法的时间性能表现如下图所示:
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.
对于这个题目,我毫无头绪,当我在Discuss上看懂这个解法的时候:https://oj.leetcode.com/discuss/10337/accepted-o-n-solution我觉得这个解法实在是太妙了!这个链接有关于这个解法的idea:https://oj.leetcode.com/discuss/5469/is-the-length-of-t-considered-constant-or-m
下面先贴出这个解法的代码:
string minWindow(string S, string T) { int count = T.size(); int require[128] = { 0 }; bool charSet[128] = { false }; for (int n = 0; n < count; ++n) { require[T ]++; charSet[T ] = true; } int i = -1, j = 0; int minLen = INT_MAX, minIdx = 0; while (i < (int)S.size() && j < (int)S.size()) { if (count) { i++; require[S[i]]--; if (charSet[S[i]] && require[S[i]] >= 0) count--; } else { if (minLen > i - j + 1) { minLen = i - j + 1; minIdx = j; } require[S[j]]++; if (charSet[S[j]] && require[S[j]] > 0) count++; j++; } } return (minLen == INT_MAX ? "" : S.substr(minIdx, minLen)); }
直观地理解这个算法是比较困难的,建议用一些例子跑起来,这样会比较容易理解这个算法为什么能到期望的目的。总之我很为这个解法而惊叹!
这个算法的时间性能表现如下图所示:
相关文章推荐
- Minimum Window Substring 最小子串窗口@LeetCode
- [leetcode]Minimum Window Substring
- [leetcode 76] Minimum Window Substring
- leetcode:Minimum Window Substring(最小覆盖子串)【面试算法题】
- LeetCode – Refresh – Minimum Window Substring
- Leetcode Minimum Window Substring
- Leetcode: Minimum Window Substring
- LeetCode Minimum Window Substring
- Minimum Window Substring leetcode java
- LeetCode | Minimum Window Substring
- LeetCode(76) Minimum Window Substring
- Java for LeetCode 076 Minimum Window Substring
- 【LeetCode】 Minimum Window Substring
- LeetCode76——Minimum Window Substring
- LeetCode:Minimum Window Substring
- leetcode Minimum Window Substring答案解析
- LeetCode76 Minimum Window Substring
- [Leetcode]Minimum Window Substring
- LeetCode_OJ【76】Minimum Window Substring
- leetcode- Minimum Window Substring