题意:给出一个字符串,求出其子串中包含能组成给定字符串的最短子串。
思路:先用hash map判断是否包含。枚举以每个字母结尾的子串。用一个指针指向该子串的启示位置。
class Solution {
public:
string minWindow(string s, string t) {
string temps = "";
map<char, int> testa;
map<char, int> testb;
for(int i = 0; i < s.length(); ++ i) testa[s[i]] ++;
for(int i = 0; i < t.length(); ++ i) testb[t[i]] ++;
if(!check(testa, testb)) return temps;
map<char, int> myc;
map<char, int> myhave;
for(int i = 0; i < t.length(); ++ i) {
myc[t[i]] ++;
}
vector<int> p(s.length(), -1);
int st = 0;
for(int i = 0; i < s.length(); ++ i) {
//if(ch[s[i] - 'A'] == -2) continue;
if(!myc[s[i]]) continue;
myhave[s[i]] ++;
if(check(myhave, myc)) {
while(check(myhave, myc)) {
if(!myc[s[st]]) {
st ++;
continue;
}
myhave[s[st]] --;
p[i] = st;
st ++;
}
}
}
int shortest = INT_MAX;
int r,l;
r = l = 0;
for(int i = 0; i < p.size(); ++ i) { //cout << p[i] << endl;
if(p[i] != -1 && shortest > i - p[i] + 1) {
shortest = i - p[i] + 1;
r = p[i];
l = i;
}
}
return s.substr(r, l - r + 1);
}
bool check(map<char, int> a, map<char, int> b) {
std::map<char, int>::iterator it = b.begin();
for(; it !=b.end(); it ++) {
if(a[it->first] < it->second) return false;
}
return true;
}
};
还有改进空间。
在空间上,可以只保留字串开始位置和长度。
在时间上,可以用一个计数器记录未满足要求的字母的个数。
class Solution {
public:
string minWindow(string s, string t) {
vector<int> m(128, 0);
for(int i = 0; i < t.length(); ++ i) m[t[i]] ++;
int c = t.length();
int r,l; r = l = 0;
int head = 0;
int d = INT_MAX;
for(int i = 0; i < s.length(); i ++) {
if(m[s[i]] -- > 0) c --;
//cout << c << endl;
while(c == 0) {
r = i; //cout << c << endl;
if(d > r - l + 1) d = r - l + 1, head = l;
if(m[s[l ++]] ++ == 0) c ++;
}
}
//cout << head << endl;
if(d == INT_MAX) return "";
else return s.substr(head, d);
}
};