您的位置:首页 > 其它

[Leetcode] Minimum Window Substring

2014-04-03 15:30 567 查看
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.

要求复杂度为O(n),只要扫描一遍数组即可,大致做法是设一个start和一个end表示窗口的起始与结束位置,先从先向后匹配end,当找到可容纳T的窗口后再从前而匹配start,去掉无用的元素。具体做法为使用两个哈希表hasCvd与need2Cv,分别表示已经找到的某个字母的匹配与需要找到的匹配。

class Solution {
public:
string minWindow(string S, string T) {
int start = 0, end = 0;
int min_start = 0, min_end = 0;
int min_len = INT_MAX;
vector<int> hasCvd(256 ,0);
vector<int> need2Cv(256, 0);
for (int i = 0; i < T.length(); ++i) {
++need2Cv[T[i]];
}
int validCnt = 0;
for (end = 0; end < S.length(); ++end) {
++hasCvd[S[end]];
if (need2Cv[S[end]] == 0) continue;
if (hasCvd[S[end]] <= need2Cv[S[end]]) ++validCnt;
if (validCnt == T.length()) {
while(hasCvd[S[start]] > need2Cv[S[start]]) {
--hasCvd[S[start]];
++start;
}
if(min_len > (end - start)) {
min_len = end - start + 1;
min_start = start;
min_end = end;
}
}
}
return (min_len == INT_MAX) ? "" : S.substr(min_start, min_len);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: