一、滑动窗口法
目的是为了减少 while 循环。
用于解决数组中定长问题
二、滑动窗口法模版
class Solution {
public String minWindow(String s, String t) {
HashMap<Character, Integer> need = new HashMap();
HashMap<Character, Integer> window = new HashMap();
//need存放的不重复的字符出现的次数
for (char c : t.toCharArray())
need.put(c, need.getOrDefault(c, 0) + 1);
//left,right 表示滑动窗口的左右指针
int left = 0, right = 0;
int valid = 0;
while (right < s.length()) {
char c = s.charAt(right);
right++;
//进行窗口数据的更新
//....
//判断是否需要收缩(即已经找到了合适的覆盖串)
while (valid == need.size()) {
char c1 = s.charAt(left);
//左移窗口
left++;
//进行窗口内数据的一系列更新
}
}
}
}
三、滑动窗口法相关题型
1.leetcode 209 长度最小的子数组
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4]
输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
提示:
1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 105
进阶:
如果你已经实现 O(n) 时间复杂度的解法, 请尝试设计一个 O(n log(n)) 时间复杂度的解法。
解答:
public class Solution {
public int minSubArrayLen(int target, int[] nums) {
if (nums == null || nums.length == 0) return 0;
int i = 0, j = 0, result = nums.length + 1, total = 0;
while (j < nums.length) {
total += nums[j];
j++;
while (total >= target) {
result = Math.min(result, j - i);
total -= nums[i];
i++;
}
}
return result == nums.length + 1 ? 0 : result;
}
}
2.leetcode 1456 定长子串中元音的最大数目
给你字符串 s 和整数 k 。
请返回字符串 s 中长度为 k 的单个子字符串中可能包含的最大元音字母数。
英文中的 元音字母 为(a, e, i, o, u)。
示例 1:
输入:s = “abciiidef”, k = 3
输出:3
解释:子字符串 “iii” 包含 3 个元音字母。
示例 2:
输入:s = “aeiou”, k = 2
输出:2
解释:任意长度为 2 的子字符串都包含 2 个元音字母。
示例 3:
输入:s = “leetcode”, k = 3
输出:2
解释:“lee”、“eet” 和 “ode” 都包含 2 个元音字母。
示例 4:
输入:s = “rhythms”, k = 4
输出:0
解释:字符串 s 中不含任何元音字母。
示例 5:
输入:s = “tryhard”, k = 4
输出:1
提示:
1 <= s.length <= 10^5
s 由小写英文字母组成
1 <= k <= s.length
解答:
class Solution {
public int maxVowels(String s, int k) {
//边界条件判断
if (s == null || s.length() == 0)
return 0;
char[] chars = s.toCharArray();
Set<Character> set = new HashSet<>();
//a, e, i, o, u
set.add('a');
set.add('e');
set.add('i');
set.add('o');
set.add('u');
int i = 0, j = k - 1, count = 0, res = 0;
//首先看前K个 中包含有多少个元音
for (int m = 0; m < k; m++) {
if (set.contains(chars[m]))
count++;
}
//找最大的COUNT 保存到 RES中
res = Math.max(count, res);
//开始遍历整个字符数组
while (j < chars.length - 1) {
if (set.contains(chars[i]))
count--;
i++;
j++;
if (set.contains(chars[j]))
count++;
res = Math.max(count, res);
}
return res;
}
}
推广
云数据库RDS MySQL 版是全球最受欢迎的开源数据库之一,作为开源软件组合 LAMP(Linux + Apache + MySQL + Perl/PHP/Python) 中的重要一环,广泛应用于各类应用场景。
点击查看->>> 云数据库新年钜惠,新用户1折起,爆款5-8折,MySQL 1年仅需19.9元.
云服务器ECS
云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的云计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。专业的售前技术支持,协助您选择最合适配置方案
点击查看->>> 弹性计算10年深厚技术积淀,技术领先、性能优异、 稳如磐石.
短信服务(Short Message Service)是广大企业客户快速触达手机用户所优选使用的通信能力。调用API或用群发助手,即可发送验证码、通知类和营销类短信;国内验证短信秒级触达,到达率最高可达99%;国际/港澳台短信覆盖200多个国家和地区,安全稳定,广受出海企业选用。
点击查看->>> 短信服务新用户 0元免费试用.