#include <iostream>
#include <unordered_map>
#include <climits>
using namespace std;
class Solution {
public:
string minWindow(string S, string T) {
if(S.empty()) {
return "";
}
unordered_map<char, int> expectedToFind;
unordered_map<char, int> hasFound;
for(int i = 0; i < T.length(); ++i) {
expectedToFind[T[i]]++;
}
int minLength = INT_MAX;
int minStart = 0;
int minEnd = 0;
int count = 0;
for(int start = 0, end = 0; end < S.length(); end++) {
if(expectedToFind[S[end]] > 0) {
hasFound[S[end]]++;
}
if(expectedToFind[S[end]] > 0 && hasFound[S[end]] <= expectedToFind[S[end]]) {
count++;
}
if(count == T.length()) {
while(expectedToFind[S[start]] == 0 || hasFound[S[start]] > expectedToFind[S[start]]) {
if(hasFound[S[start]] > expectedToFind[S[start]] ) {
hasFound[S[start]]--;
}
start++;
}
int wLen = end - start + 1;
if(wLen < minLength) {
minLength = wLen;
minStart = start;
minEnd = end;
}
}
}
return count == T.length() ? S.substr(minStart, minEnd - minStart + 1): "";
}
};
int main(int argc, char *argv[])
{
Solution s;
std::cout << s.minWindow("a", "a") << std::endl;
return 0;
}
4/27/2014
Leetcode -- Minimum Window Substring
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment