您的位置:首页 > 其它

LeetCode-Minimum Window Substring

2014-08-09 23:36 441 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息