力扣76. 最小覆盖子串(滑动窗口)

要注意的细节比较多,主要是还需要优化查询满足条件的方式
1 class Solution { 2 public: 3 vector<int> cnt, need; 4 // bool judge(string t) { //该查询方法会超时 5 // for(auto i : t) { 6 // if (cnt[i] < need[i]) 7 // return false; 8 // } 9 // return true; 10 // } 11 string minWindow(string s, string t) { 12 unordered_map<char, int> cnt, need; // 为什么不用vector直接记录:为了可以方便地统计不重复的字符个数 13 int start = 0, len = INT32_MAX; // 记录子串起始点与长度 14 int left = 0, right = 0; //滑动窗口边界,一般为[left,right) 15 int valid = 0; //记录当前满足字符的个数 16 for (auto i : t) { 17 need[i]++; 18 } 19 while (right < s.length()) { 20 if (need.count(s[right])) { 21 cnt[s[right]]++; 22 if (cnt[s[right]] == need[s[right]]) {valid++;} //此处一定要在cnt[s[right]] == need[s[right]]的边界条件上进行valid++ 23 } 24 right++; 25 while (valid == need.size()) { //当满足的个数达到时,将窗口左界右移到个数不满足为止。 26 int temp = right - left; 27 if (temp < len) { 28 len = min(temp, len); 29 start = left; 30 } 31 if (need.count(s[left])) { 32 if (cnt[s[left]] == need[s[left]]) {valid--;} 33 cnt[s[left]]--; 34 } 35 left++; 36 } 37 } 38 if (len == INT32_MAX) {len = 0;} 39 return s.substr(start, len); 40 } 41 };
浙公网安备 33010602011771号