Note
If there is no such window in source that covers all characters in target, return the emtpy string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in source.
Example
source = "ADOBECODEBANC" target = "ABC" Minimum window is "BANC".
Challenge
Can you do it in time complexity O(n) ?
Clarification
Should the characters in minimum window has the same order in target?
- Not necessary.
class Solution {
public:
/**
* @param source: A string
* @param target: A string
* @return: A string denote the minimum window
* Return "" if there is no such a string
*/
string minWindow(string &source, string &target) {
int toFind[256]={0};
int found[256] = {0};
int foundCount = 0;
int minWindow = source.length()+1;
string ret = "";
for(char c : target)
toFind[c]++;
for(int i = 0, j = 0; j < source.length(); j++) {
if (++found[source[j]] <= toFind[source[j]] && toFind[source[j]] > 0)
foundCount++;
if (foundCount >= target.length()) {
while(found[source[i]] > toFind[source[i]])
--found[source[i++]];
if (j - i + 1 < minWindow) {
minWindow = j-i+1;
ret = source.substr(i, minWindow);
}
}
}
return ret;
}
};
This algorithm is by far the best that I found. Could you explain more the algorithm ?
ReplyDeletesee here: http://leetcode.com/2010/11/finding-minimum-window-in-s-which.html
ReplyDelete