(四)LeetCode热题100——子串

1. 和为 K 的子数组

题目来源
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的子数组的个数 。子数组是数组中元素的连续非空序列。

示例 1:
输入:nums = [1,1,1], k = 2
输出:2

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int, int> hash;
        int sum = 0;
        int ret = 0;
        hash[0] = 1;
        // 前缀和
        for (auto & n : nums){
            sum += n;
            if (hash.count(sum - k)) ret += hash[sum - k];
            hash[sum]++;
        }
        return ret;
    }
};

2. 滑动窗口最大值

题目来源
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。返回 滑动窗口中的最大值 。

示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:

滑动窗口的位置                最大值
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int n = nums.size();
        priority_queue<pair<int, int>> q;
        for (int i = 0; i < k; ++i){
            q.push({nums[i], i});
        }
        vector<int> ret;
        ret.push_back(q.top().first);
        for (int i = k; i < n; ++i){
            // 单调队列,根据他们的下标 
            while (!q.empty() && i - k >= q.top().second) q.pop();
            q.push({nums[i], i});
            ret.push_back(q.top().first);
        }
        return ret;
    }
};

3. 最小覆盖子串

题目来源
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。

注意:
对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
如果 s 中存在这样的子串,我们保证它是唯一的答案。

示例 1:
输入:s = “ADOBECODEBANC”, t = “ABC”
输出:“BANC”
解释:最小覆盖子串 “BANC” 包含来自字符串 t 的 ‘A’、‘B’ 和 ‘C’。

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<int, int> hash;
        for (auto & c : t) hash[c]++;
        int n = s.size();
        int left = 0, right = 0;
        int l = 0, r = n - 1;
        int count = hash.size();
        bool flag = false;
        // 滑动窗口
        while (right < n){
            hash[s[right]]--;
            if (hash[s[right]] == 0) count--;
            while (count == 0){
                flag = true;
                if (right - left < r - l){
                    l = left, r = right;
                }
                hash[s[left]]++;
                if (hash[s[left]] > 0) ++count;
                ++left;
            }
            ++right;
        }
        if (flag) return s.substr(l, r - l + 1);
        return "";
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三问走天下

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值