jiazhongchen

leetcode76

Feb 22nd, 2022
758
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string minWindow(string s, string t) {
  4.         string ans;
  5.         int n = s.size();
  6.         int minLen = INT_MAX;
  7.         int index = -1;
  8.         if (s.size() < t.size()) return ans;
  9.         unordered_map<char, int> hashT;
  10.         unordered_map<char, int> hashS;
  11.         for (char c : t) ++hashT[c];
  12.         for (int i = 0, j = 0; j < n; ++j) {
  13.             ++hashS[s[j]];
  14.             while (checkValid(hashS, hashT)) {
  15.                 int len = j - i + 1;
  16.                 if (len < minLen) {
  17.                     minLen = len;
  18.                     index = i;
  19.                 }
  20.                 if (--hashS[s[i]] == 0) hashS.erase(s[i]);
  21.                 ++i;
  22.             }
  23.         }
  24.         return minLen == INT_MAX ? "" : s.substr(index, minLen);
  25.     }
  26.     bool checkValid(unordered_map<char, int>& hashS, unordered_map<char, int>& hashT) {
  27.         for (auto item : hashT) {
  28.             if (hashS.find(item.first) == hashS.end()) return false;
  29.             if (hashS[item.first] < item.second) return false;
  30.         }
  31.         return true;
  32.     }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment