您的位置:首页 > 其它

LEETCODE: Minimum Window Substring

2014-12-26 13:47 351 查看
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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LEETCODE string 算法