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 = "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); } };
Minimum Window Substring -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/45013691