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:Code:
<span style="font-size:14px;">class Solution {
public:
string minWindow(string S, string T) {
int lengthS = S.size(), lengthT = T.size();
if (lengthT > lengthS) return "";
unordered_map<char, int> hashTable;
for (int i = 0; i < lengthT; i++)
hashTable[T[i]]++;
int count = 0, begin = 0, end = 0;
for (; end < lengthS; end++)
if (hashTable.find(S[end]) != hashTable.end()) {
hashTable[S[end]]--;
if (hashTable[S[end]] >= 0) count++;
if (count == lengthT) break;
}
if (count != lengthT) return "";
for (; begin <= end; begin++)
if (hashTable.find(S[begin]) == hashTable.end()) continue;
else if (hashTable[S[begin]] < 0) hashTable[S[begin]]++;
else if (hashTable[S[begin]] == 0) break;
int minLength = end-begin+1;
int result = begin;
end++;
for (; end < lengthS; end++)
if (S[begin] == S[end]) {
begin++;
for (; begin <= end; begin++)
if (hashTable.find(S[begin]) == hashTable.end()) continue;
else if (hashTable[S[begin]] < 0) hashTable[S[begin]]++;
else if (hashTable[S[begin]] == 0) break;
if (end-begin+1 < minLength) {
minLength = end-begin+1;
result = begin;
}
} else {
if (hashTable.find(S[end]) != hashTable.end())
hashTable[S[end]]--;
}
return S.substr(result, minLength);
}
};</span>

本文介绍了一种在字符串S中寻找包含字符串T所有字符的最短子串的算法,复杂度为O(n)。通过使用哈希表跟踪目标字符及其出现次数,该算法能够高效地确定满足条件的最小窗口。

122

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



