Minimum Window Substring -- leetcode
2015-04-12 20:46
387 查看
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.
基本思路:
1. 维持一个窗口,使得[left, right] 包含子串T。
2. left尽可能向右靠近right,直到再多移动一步,窗口就不能包含字串T。
3. 在窗口向右滑动过程中,记录下最小的窗口。
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.
基本思路:
1. 维持一个窗口,使得[left, right] 包含子串T。
2. left尽可能向右靠近right,直到再多移动一步,窗口就不能包含字串T。
3. 在窗口向右滑动过程中,记录下最小的窗口。
class Solution { public: string minWindow(string S, string T) { vector<int> modal(256); vector<int> actual(256); for (auto ch: T) ++modal[ch]; int leftWnd = 0, rightWnd = S.size(); int count = 0; for (int left = 0, right = 0; right < S.size(); ++right) { if (++actual[S[right]] <= modal[S[right]]) ++count; if (count == T.size()) { while (!modal[S[left]] || actual[S[left]] > modal[S[left]]) --actual[S[left++]]; if (right - left < rightWnd - leftWnd) { rightWnd = right; leftWnd = left; } } } if (count < T.size()) return ""; return S.substr(leftWnd, rightWnd - leftWnd + 1); } };
相关文章推荐
- LeetCode 76 Minimum Window Substring
- LeetCode: Minimum Window Substring
- [leetcode] Minimum Window Substring
- LeetCode-76-Minimum Window Substring 尺取法+字典
- Leetcode---Minimum Window Substring
- 【leetcode 76】 Minimum Window Substring
- 【LeetCode 76】 Minimum Window Substring
- leetcode: Minimum Window Substring
- [LeetCode]Minimum Window Substring
- leetcode 76: Minimum Window Substring
- [LeetCode] Minimum Window Substring
- LeetCode Online Judge 题目C# 练习 - Minimum Window Substring
- [Leetcode]Minimum Window Substring
- Leetcode-Minimum Window Substring
- LeetCode 笔记系列16.1 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
- [leetcode刷题系列]Minimum Window Substring
- [leetcode] Minimum Window Substring
- leetcode - Minimum Window Substring
- leetcode-Minimum Window Substring
- LeetCode "Minimum Window Substring" - STAR