1. var minWindow = function (s, t) {
    2. let need = {};//需要覆盖的字符串频数
    3. let window = {};//滑动窗口的字符串频数
    4. for (let a of t) {
    5. need[a] = (need[a] || 0) + 1;//统计t中字符频数
    6. }
    7. //左右指针
    8. let left = 0,
    9. right = 0;
    10. let valid = 0;//滑动窗口中能覆盖的字符种类数
    11. let start = 0,//最小覆盖子串的起始索
    12. len = Number.MAX_VALUE;//最小覆盖子串长度
    13. while (right < s.length) {
    14. let c = s[right];//进入滑动窗口右边的字符
    15. right++;//右移窗口
    16. if (need[c]) {//如果当前字符在need字符中 更新window中字符数
    17. window[c] = (window[c] || 0) + 1;
    18. if (window[c] == need[c]) {//如果当前窗口和需要的字符数量一致时,字符种类+1
    19. valid++;
    20. }
    21. }
    22. while (valid == Object.keys(need).length) {//字符种类与需要的字符个数一致时,就收缩窗口
    23. if (right - left < len) {//当前窗口长度小于之前窗口的长度len 更新最小覆盖子串的起始位置和长度
    24. start = left;
    25. len = right - left;
    26. }
    27. let d = s[left];//需要被移除的字符
    28. left++;//左移窗口 从窗口中移除字符
    29. if (need[d]) {//如果在需要的字符中 更新window中字符数
    30. if (window[d] == need[d]) {//如果当前窗口和需要的字符数量一致时,字符种类-1
    31. valid--;
    32. }
    33. window[d]--;
    34. }
    35. }
    36. }
    37. //没有找到覆盖子串 返回'' 否则返回覆盖子串
    38. return len == Number.MAX_VALUE ? "" : s.substr(start, len);
    39. };
    1. class Solution {
    2. public:
    3. unordered_map <char, int> ori, cnt;
    4. bool check() {
    5. for (const auto &p: ori) {
    6. if (cnt[p.first] < p.second) {
    7. return false;
    8. }
    9. }
    10. return true;
    11. }
    12. string minWindow(string s, string t) {
    13. for (const auto &c: t) {
    14. ++ori[c];
    15. }
    16. int l = 0, r = -1;
    17. int len = INT_MAX, ansL = -1, ansR = -1;
    18. while (r < int(s.size())) {
    19. if (ori.find(s[++r]) != ori.end()) {
    20. ++cnt[s[r]];
    21. }
    22. while (check() && l <= r) {
    23. if (r - l + 1 < len) {
    24. len = r - l + 1;
    25. ansL = l;
    26. }
    27. if (ori.find(s[l]) != ori.end()) {
    28. --cnt[s[l]];
    29. }
    30. ++l;
    31. }
    32. }
    33. return ansL == -1 ? string() : s.substr(ansL, len);
    34. }
    35. };
    36. 作者:LeetCode-Solution
    37. 链接:https://leetcode-cn.com/problems/minimum-window-substring/solution/zui-xiao-fu-gai-zi-chuan-by-leetcode-solution/
    38. 来源:力扣(LeetCode
    39. 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。