Given a string source and a string target, find the minimum window in source which will contain all the characters in target.
Clarification
Should the characters in minimum window has the same order in target?
- Not necessary.
Example
For source = "ADOBECODEBANC"
, target = "ABC"
, the minimum window is "BANC"
Challenge
思路是先统计目标中的每个字符出现了多少次,然后在需检测的string中每读到一个目标字符,就检查下头部有木有可以删去的
Can you do it in time complexity O(n) ?
的字符,统计长度最小值, 用hashmap实现:
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) {
// write your code here
vector<pair<char,int>> vec;
unordered_map<char, int> map_t;
unordered_map<char, int> map_s;
unordered_set<char> set_for_s;
string res="";
int len_s=0;
int len_t=0;
int len=INT_MAX;
for (int i=0;i<target.size();i++) {
if (map_t.find(target[i]) == map_t.end()) {
map_t[target[i]]=1;
len_t++;
}
else
map_t[target[i]]= map_t[target[i]]+1;
}
for (int i = 0; i<source.size();i++) {
if (map_t.find(source[i])!= map_t.end()) {
vec.push_back(make_pair(source[i],i));
if (map_s.find(source[i]) != map_s.end()) {
map_s[source[i]]=map_s[source[i]]+1;
} else {
map_s[source[i]]=1;
}
if (map_s[source[i]]>= map_t[source[i]] && set_for_s.find(source[i])== set_for_s.end()) {
set_for_s.insert(source[i]);
len_s++;
}
char c=vec[0].first;
while (map_s[c]>map_t[c]) {
map_s[c]=map_s[c]-1;
vec.erase(vec.begin());
c=vec[0].first;
}
if (len_s == len_t) {
int l = vec[vec.size()-1].second - vec[0].second + 1;
if (l<len){
len=l;
res=source.substr(vec[0].second, l);
}
}
}
}
return res;
}
};