滑动窗口题目(中等)

本文介绍了两个编程问题的解决方案:1.寻找不超过K个不同字符的最长子字符串长度,通过滑动窗口和哈希映射实现;2.最大化水果放入两个篮子的数量,同样利用滑动窗口策略。解题关键在于窗口收缩时机的判断,以及利用哈希映射统计窗口内元素种类。
摘要由CSDN通过智能技术生成

3.Longest Substring with maximum K Distinct Characters (medium)

问题描述

给定一个字符串,找出其中不超过 K 个不同字符的最长子字符串的长度。
Example 1:

Input: String="araaci", K=2
Output: 4
Explanation: The longest substring with no more than '2' distinct characters is "araa".

Example 2:

Input: String="araaci", K=1
Output: 2
Explanation: The longest substring with no more than '1' distinct characters is "aa".

Example 3:

Input: String="cbbebi", K=3
Output: 5
Explanation: The longest substrings with no more than '3' distinct characters are "cbbeb" & "bbebi".

Example 4:

Input: String="cbbebi", K=10
Output: 6
Explanation: The longest substring with no more than '10' distinct characters is "cbbebi".

解题的关键:

1.相信看完前面两道题,这道题的关键,窗口收缩的时机大家是心里有数的,就是窗口不同字母的个数大于k的时候窗口收缩.
2.逻辑很好理解,就是实现起来需要借助一种数据结构来得到窗口不同字母的个数,hash_map,不了解的可以自行学习。问题的核心是不同字母个数,所以key储存字母,value储存个数

代码:

 int findLength(const string& input, int k) {
    unordered_map<char,int> map;
    int winstat = 0;
    int size = 0;
    int maxsize = 0;
    for(int winend=0;winend<input.size();++winend)
    {
     map[input[winend]]++;
     while(map.size() > k)//窗口收缩的时机为不同字母的个数大于k,收缩一次可能不一定满足条件,所以使用whIle
     {
         map[input[winstat]]--;
         if(map[input[winstat]] == 0)
         {map.erase(map[input[winstat]]);}
         winstat++;
    
     }
    maxsize = max(maxsize,winend-winstat+1);
    }
    return maxsize;
    }

4.Fruits into Baskets (medium)

问题描述

你正在参观一个农场收集水果。 农场有一排果树。 你会得到两个篮子,你的目标是尽可能多地采摘水果放在给定的篮子里。

你将获得一个字符数组,其中每个字符代表一棵果树。 农场有以下限制:

1.每个篮子只能装一种水果。 一个篮子可以装多少个水果是没有限制的。
2.你可以从任何一棵树开始,但一旦开始,就不能跳过任意一棵树。
3.你只能从每棵树上只摘一个水果,直到你不能摘都是后,也就是说,你的篮子里不能有第三种水果
编写一个函数来返回两个篮子中水果的最大数量。
Example 1:

Input: Fruit=['A', 'B', 'C', 'A', 'C']
Output: 3
Explanation: We can put 2 'C' in one basket and one 'A' in the other from the subarray ['C', 'A', 'C']

Example 2:

Input: Fruit=['A', 'B', 'C', 'B', 'B', 'C']
Output: 5
Explanation: We can put 3 'B' in one basket and two 'C' in the other basket. 
This can be done if we start with the second letter: ['B', 'C', 'B', 'B', 'C']

解题的关键:

1.本题跟上面的题目类似,窗口收缩的时机为,窗口内水果的种类大于2,代码就不作注释了
2.同样用hash_map,key储存水果种类,value储存个数

代码:

int fruits(vector<char> str)
{
    unordered_map<char,int> map;
    int windstat=0;
    int maxsize= 0;
    for(int windend =0;windend<str.size();++windend)
    {
        map[str[windend]]++;
        while(map.size() >= 3)
        {
            map[str[windstat]]--;
            if( map[str[windstat]] == 0)
            {
            map.erase(str[windstat]);
            }
            windstat++;
        }
        maxsize = max(maxsize,windend-windstat+1);
    }
    return maxsize;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值