滑动窗口leetcode 209和76

一、leetcode 209. 长度最小的子数组

代码:

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int n = nums.size();
        int left = 0;
        int sum = 0;
        int res = 100001;
        for(int right = 0;right <n;right++){
            sum += nums[right];
            while(sum >= target){
                res = min(res,right-left+1);
                sum -= nums[left];
                left++;
            }
        }
        if(res == 100001)
            res = 0;
        return res;
    }
};

二、leetcode76. 最小覆盖子串

代码:

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char,int> t_map;
        unordered_map<char,int> window_map;
        for(char ch:t){
            if(t_map.contains(ch)){
                t_map[ch]++;
            }else{
                t_map[ch] = 1;
            }
            window_map[ch] = 0;
        }

        int s_len = s.size();
        int left = 0;
        int ans_left = -1;
        int ans_len = INT_MAX;
        for(int right = 0; right <s_len;right++){
            if(!window_map.contains(s[right]))
                continue;
            window_map[s[right]]++;
            while(check(t_map,window_map) && left <= right){
                if(right -left+1 <ans_len){
                    ans_len = right -left +1;
                    ans_left = left;
                }
                if(t_map.contains(s[left]))
                    window_map[s[left]]--;
                left++;
            }
        }
        if(ans_left == -1) return "";
        return s.substr(ans_left,ans_len);
    }

    bool check(unordered_map<char,int>& t_map,unordered_map<char,int>& window_map){
        for(auto p:t_map){
            if(window_map[p.first] < t_map[p.first])
                return false;
        }
        return true;
    }
};

class Solution {
public:
    string minWindow(string s, string t) {
        unordered_map<char,int> t_map;
        unordered_map<char,int> window_map;
        for(char ch:t){
            if(t_map.contains(ch))
                t_map[ch]++;
            else
                t_map[ch] = 1;
        }

        int s_len = s.size();
        int left = 0;
        int window_valid_char_cnt = 0;
        string ans;
        for(int right = 0; right <s_len;right++){
            if(++window_map[s[right]] <= t_map[s[right]])
                window_valid_char_cnt++;
            while(window_map[s[left]] > t_map[s[left]]){
                window_map[s[left]]--;
                left++;
            }
            if(window_valid_char_cnt == t.size()){
                if(ans.empty() || ans.size() > right-left+1)
                    ans = s.substr(left,right-left+1);
            }
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值