Leetcode: Minimum Window Substring
2014-06-29 19:14
543 查看
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.
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.
class Solution { public: string minWindow(string S, string T) { map<char, int> charMap; int ll = 0; int len = 0; for (int i = 0; i < T.length(); ++i) { map<char, int>::iterator it = charMap.find(T[i]); if (it == charMap.end()) charMap[T[i]] = 1; else ++it->second; } int l = 0, r = 0; int count = 0; while(r != S.length()) { map<char, int>::iterator it = charMap.find(S[r++]); if (it == charMap.end()) { continue; } --it->second; if (it->second >= 0) { ++count; } if (count == T.length()) break; } if (count < T.length()) return ""; len = r; int end = 0; while (!end) { end = 1; while (l != S.length()) { map<char, int>::iterator it = charMap.find(S[l]); if (it == charMap.end()) { ++l; continue; } if (it->second < 0) { ++it->second; end = 0; ++l; } else break; } if (r-l < len) { len = r-l; ll = l; } while (r != S.length()) { map<char, int>::iterator it = charMap.find(S[r++]); if (it == charMap.end()) { continue; } --it->second; end = 0; break; } if (r == S.length() && end == 1) break; } string ret = S.substr(ll, len); return ret; } };
相关文章推荐
- [leetcode 76] Minimum Window Substring
- [Leetcode] - Minimum Window Substring
- [LeetCode] Minimum Window Substring 最小窗口子串
- LeetCode76 Minimum Window Substring(两种解法)
- LeetCode76 Minimum Window Substring
- Leetcode: Minimum Window Substring
- [leetcode]Minimum Window Substring @ Python
- [LeetCode] Minimum Window Substring
- Minimum Window Substring -- LeetCode
- 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-Minimum Window Substring
- [LeetCode] Minimum Window Substring
- LeetCode Minimum Window Substring