leetcode: Minimum Window Substring
2014-07-05 14:22
253 查看
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中字符,头指针再走,直到再走它和尾指针间就不包含所有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中字符,头指针再走,直到再走它和尾指针间就不包含所有T中字符为止,记录所有情况中最短的
class Solution { public: string minWindow(string S, string T) { if( S.size() < T.size() || T.empty()) return ""; unordered_map< char, int> appear; unordered_map< char, int> expect; for( int i = 0; i < T.size(); ++i) ++expect[T[i]]; int length = INT_MAX, start = 0, appear_time = 0, min_start = 0;//最小窗口长度,起始位置,出现次数,最小窗口起始 for( int end = 0; end < S.size(); ++end){ if( expect[S[end]] > 0 ){ ++appear[S[end]]; if( appear[S[end]] <= expect[S[end]] ){ ++appear_time; } } if( appear_time == T.size()){ while( appear[S[start]] > expect[S[start]] || expect[S[start]] == 0){ --appear[S[start]]; ++start; } if( length > end -start + 1){ length = end - start + 1; min_start = start; } } } if( length == INT_MAX) return ""; return S.substr( min_start, length); } };
相关文章推荐
- LeetCode-Minimum Window Substring
- 【LeetCode】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][Java] Minimum Window Substring
- leetcode 76: Minimum Window Substring
- LeetCode076 Minimum Window Substring
- LeetCode(76) Minimum Window Substring
- [leetcode]Minimum Window Substring @ Python
- [LeetCode] Minimum Window Substring
- leetcode -- Minimum Window Substring
- [LeetCode] Minimum Window Substring
- LeetCode Minimum Window Substring
- [LeetCode][Java] Minimum Window Substring
- 【Leetcode】Minimum Window Substring
- LeetCode —— Minimum Window Substring
- Leetcode231: Minimum Window Substring