Description
Problem Link
对于给定的字符串S,T,求S中包含T中所有字符的最短的子串。要求时间复杂度O(n)
e.g.
S = "ADOBECODEBANC"
T = "ABC"
return "BANC"
Possible Solution
分析:在这道题中,如果子串的结束位置固定了,那么最优解的开始位置也是固定的。而且随着end的增大,begin只会变大,不会变小。
基本思路:固定end,在满足有解得情况下,尽可能让begin变大。
如何判断有解?
代码中用一个bucket[128]来统计每个字符在T中出现的次数。
用一个counter[128]来实时统计,每个字符在当前的[begin,end]中出现的次数。
用一个remain变量来统计,还有多少字符的bucket>counter。当所有字符的bucket均<=counter,即可认为是有解的。
附代码:
class Solution {
private:
static const int SIZE = 128+5;
public:
string minWindow(string s, string t) {
int n = t.size();
int m = s.size();
vector<int> bucket(SIZE,0);
for (int i = 0; i < n; ++i)
++bucket[t[i]];
int remain = n;
int ansbegin = -1;
int anslen = -1;
vector<int> counter(SIZE,0);
int begin = 0;
for (int end = 0; end < m; ++end) {
if (bucket[s[end]] > counter[s[end]]) {
remain --;
}
counter[s[end]] ++;
while (remain == 0) {
int len = end - begin + 1;
if (ansbegin == -1 || len < anslen) {
anslen = len;
ansbegin = begin;
}
if (bucket[s[begin]] <= counter[s[begin]] - 1) {
--counter[s[begin]];
begin++;
}
else break;
}
}
if (ansbegin == -1) return "";
else return s.substr(ansbegin,anslen);
}
};