class Solution {
public:
string minWindow(string s, string t) {
int i=0,j=0;
unordered_map<char,int> needMap;
int needCnt=t.size();
//needMap 代表:需要某个字符(key)若干个(value). needCnt表示当前缺失的字符数量。
string res="";
for (auto item : t){
needMap[item]+=1;
}
while(j<s.size()){
if(needMap.count(s[j])){
if(needMap[s[j]]>0){
needCnt--;
}
needMap[s[j]]--;
}
while(needCnt==0){
if((j-i+1)<res.size()||res.size()==0){
res=s.substr(i,j-i+1);
}
if(needMap.count(s[i])){
if(needMap[s[i]]==0){
needCnt++;
}
needMap[s[i]]++;
}
i+=1;
}
j+=1;
}
return res;
}
};
最后一个测试用例超出时间限制,
使用字符数组替换哈希表:哈希表需要计算哈希值和内存分配,而字符数组只需要访问数组元素,因此速度更快。因此,可以将 unordered_map<char, int> needMap; 替换为 int need[128] = {0};,其中 128 是字符集大小。
另外 if (j - i < minLen) { // 不用 substr 函数
minLen = j - i;
start = i;
}
class Solution {
public:
string minWindow(string s, string t) {
int need[128] = {0};
int needCnt = t.size();
for (char c : t) {
need[c]++;
}
int i = 0, j = 0, start = 0, len = INT_MAX;
while (j < s.size()) {
if (need[s[j]] > 0) { // 当前字符是 t 中的字符
needCnt--;
}
need[s[j]]--;
j++;
while (needCnt == 0) { // 找到包含 t 所有字符的子串
if (j - i < len) {
start = i;
len = j - i;
}
if (need[s[i]] == 0) { // i 指向的字符是 t 中的字符
needCnt++;
}
need[s[i]]++;
i++;
}
}
return len == INT_MAX ? "" : s.substr(start, len);
}
};