您的位置:首页 > 其它

[LeetCode]Minimum Window Substring

2013-05-30 10:25 393 查看
class Solution {
//need2FT + hasFT + two pointer + count(check if satisfied)
//O(n)
public:
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int lenT = T.size();
int lenS = S.size();
if(lenT <= 0 || lenT > lenS) return string("");//illegal input
int need2FT[256] = {0};
int hasFT[256] = {0};
for (int i = 0; i < lenT; ++i)//init need2FT
need2FT[T[i]]++;
int start, end;//two pointer to sliding window
start = end = 0;
int count = 0;
int minStart, minEnd, minLen;
minLen = INT_MAX;
for ( ; end < lenS; ++end)
{
if(0 == need2FT[S[end]]) continue;//unrelated character
hasFT[S[end]]++;
if (hasFT[S[end]] <= need2FT[S[end]])
count++;
if (count == lenT)//maintain the minimum sliding window
{
while (hasFT[S[start]] > need2FT[S[start]] || 0 == need2FT[S[start]])
{
if(0 != need2FT[S[start]])
hasFT[S[start]]--;
start++;
if(start >= lenS)
break;
}
int newWinLen = end-start+1;
if (newWinLen < minLen)
{
minStart = start;
minEnd = end;
minLen = newWinLen;
}
}
if(start >= lenS) break;

}
if(minLen == INT_MAX) return string("");
//then return the qualified sliding window
return S.substr(minStart, minLen);
}
};

second time

class Solution {
public:
string minWindow(string S, string T) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> cntTable(256, 0);
vector<int> checkTable(256, 0);
for(int i = 0; i < T.size(); ++i) checkTable[T[i]]++;
//find the first window
int validCnt = 0;
int end;
for(end = 0; end < S.size(); ++end)
{
if(cntTable[S[end]] < checkTable[S[end]]) validCnt++;
cntTable[S[end]]++;
if(validCnt == T.size()) break;
}
if(end == S.size()) return "";
int minStart = 0;
while(minStart < S.size() && cntTable[S[minStart]] > checkTable[S[minStart]]) cntTable[S[minStart++]]--;
int minEnd = end;
//try to find a minimum one
int curStart = minStart;
for(int i = minEnd+1; i < S.size(); ++i)
{
cntTable[S[i]]++;
int newStart = curStart;
while(cntTable[S[newStart]] > checkTable[S[newStart]])
{
cntTable[S[newStart]]--;
newStart++;
}
curStart = newStart;
if(i-newStart < minEnd-minStart) minStart = newStart, minEnd = i;
}

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