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.
两个指针,start,end。end往后面搜。存在满足要求的后,尽量压缩start。
class Solution {
public:
string minWindow(string S, string T) {
int c[256] = {0};
bool cb[256] = {0};
int cnt = T.size();
for (char i: T) c[(int)i]++, cb[(int)i] = true;
int start = 0, end = 0;
int ls = S.size();
int minlen = 10000;
string minstr = "";
while (end < ls && start < ls) {
if (cb[S[end]]) {
c[S[end]]--;
if (c[S[end]] >= 0) cnt--;
while (cnt == 0) {
if (cb[S[start]] == false) start++;
else if (c[S[start]] < 0) {
c[S[start]]++;
start++;
} else {
break;
}
}
if (cnt == 0) {
if (end - start + 1 < minlen) {
minlen = end - start + 1;
minstr = S.substr(start, minlen);
}
c[S[start]]++;
start++;
cnt++;
}
}
end++;
}
return minstr;
}
};

本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的算法。使用两个指针,start 和 end,从S的起始位置开始遍历。当找到满足条件的子串时,尝试尽可能地压缩 start 以减少子串长度,直至无法进一步缩小。此过程确保了最终找到的子串是最小覆盖子串。
769

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



