您的位置:首页 > 其它

LeetCode - Minimum Window Substring

2014-02-26 21:26 429 查看
Minimum Window Substring

2014.2.26 21:17

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.

Solution:

  First of all, it's important to understand the definition of "window substring".

  For two strings s1 and s2, if ss is a substring of s1, and you can pick out some letters from ss to form s2, ss is a valid window substring of s2 in s1.

  A window substring may contain redundant letters. That's why you have to find the "minimum", that contains the least number of redundant letters.

  My solution is linear and goes from left to right. A simple hash table is used to count the occurence of all letters. Here the letters are limited to ASCII characters only.

  Total time complexity is O(n). Space complexity is O(1).

Accepted code:

// 4CE, 5WA, 1AC, O(n) solution, mein Gott (O_o)(>_<)(u_u)(x_X)
class Solution {
public:
string minWindow(string S, string T) {
int i;
int tc[256];
int c[256];
int cc;
int slen, tlen;
int ll, rr;
int mll, mrr;

slen = (int)S.length();
tlen = (int)T.length();
if (slen == 0 || tlen == 0 || slen < tlen) {
return "";
}

for (i = 0; i < 256; ++i) {
c[i] = 0;
tc[i] = 0;
}

for (i = 0; i < tlen; ++i) {
++tc[T[i]];
}
cc = 0;

mll = -1;
mrr = -1;
ll = 0;
while (ll < slen && tc[S[ll]] == 0) {
// skip irrelavant letters
++ll;
}
if (ll == slen) {
// S and T have no letters in common
return "";
}

rr = ll;
while (rr < slen) {
++c[S[rr]];
if (c[S[rr]] <= tc[S[rr]]) {
// S = caae, T = cae
// the window may contain redundant letters in T
++cc;
}

while (cc == tlen) {
if (mll == -1 || (rr - ll + 1) < (mrr - mll + 1)) {
// a better result is found
mll = ll;
mrr = rr;
}
// move ll to right
--c[S[ll]];
if (c[S[ll]] < tc[S[ll]]) {
--cc;
}
++ll;

while (ll < slen && tc[S[ll]] == 0) {
// skip irrelavant letters
++ll;
}
if (rr < ll) {
// ll must not go over rr
rr = ll;
}
}
++rr;
while (rr < slen && tc[S[rr]] == 0) {
++rr;
}
}

if (mll == -1) {
return "";
} else {
return S.substr(mll, mrr - mll + 1);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: