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.
直接上代码吧,其实就是先找到包含所有字符的,然后看看最左边那些是不是想要的,如果不是就去掉,看看新的长度是不是最短的。是最短的,就记下来。然后,把头上那个去掉,继续查找。
class Solution {
public:
string minWindow(string S, string T) {
vector<int> existing(256, 0);
vector<int> expected(256, 0);
int leftmost = 0;
int substrstart = -1;
int substrlength = 0x7fffffff;
int basepointer = 0;
int lack = T.size();
// Initialize the count array to count all characters in T.
for(int ii = 0; ii < T.size(); ii ++)
expected[T[ii]] ++;
for(int ii = 0; ii < S.size(); ii ++) {
// If the current character is in T, and occurs less than expected.
if(existing[S[ii]] < expected[S[ii]])
lack --;
// Record the current character.
existing[S[ii]] ++;
// If all characters in T have all show up.
if(lack == 0) {
// Remove characters that existing on the left edge of the sub string.
while(existing[S[basepointer]] > expected[S[basepointer]]) {
existing[S[basepointer]] --;
basepointer ++;
}
// Get the new length if curent one is shorter.
if(substrlength > ii - basepointer + 1) {
substrlength = ii - basepointer + 1;
substrstart = basepointer;
}
while(lack == 0) {
// Remove the character on the left edge and set new condition for loop.
existing[S[basepointer]] --;
if(existing[S[basepointer]] < expected[S[basepointer]]) {
lack ++;
}
basepointer ++;
}
}
}
return substrstart == -1 ? "" : S.substr(substrstart, substrlength);
}
};
本文介绍了一种在复杂度为O(n)的情况下,找到给定字符串中包含另一个字符串所有字符的最小窗口的方法。
107

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



