76. Minimum Window Substring
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 empty string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
非常简单
若区间[l,r]满足条件,那么至少是[l+1,r]才会满足条件,r只会增长
O(n)*O(容器),维护两个指针 l , r
class Solution {
private:
map <char, int> charset;
map <char, int> counter;
int sup;
void push(char x) {
if (charset.count(x)) {
++ counter[x];
if (counter[x] == charset[x])
++ sup;
}
}
void pop(char x) {
if (charset.count(x)) {
map <char, int> :: iterator pos = counter.find(x);
-- pos -> second;
if (pos -> second == charset[x] - 1)
-- sup;
}
}
public:
Solution() {
sup = 0;
}
string minWindow(string s, string t) {
for (int i = 0; i < t.size(); ++ i)
++ charset[t[i]];
int r = 0, reqsize = charset.size();
string now, ans;
push(s[0]);
for (int l = 0; l < s.size(); ++ l) {
while (sup < reqsize && r < s.size() - 1) {
push(s[++ r]);
}
if (sup == reqsize) {
now = s.substr(l, r - l + 1);
if (ans.empty() || ans.size() > now.size())
ans = now;
}
pop(s[l]);
}
return ans;
}
};
1597

被折叠的 条评论
为什么被折叠?



