文章目录
前言
1、最大连续1的个数 III
2、替换后的最长重复字符
3、尽可能使字符串相等
4、无重复字符的最长子串
5、长度最小的子数组
6、乘积小于 K 的子数组
一、最大连续1的个数 III(力扣1004)
分析:
最大滑窗问题
class Solution {
public int longestOnes(int[] nums, int k) {
//最大滑动窗口
int left = 0;
int right = 0;
int zeroCount = 0;
int res = 0;
while(right<nums.length){
if(nums[right]==0){
zeroCount++;
}
while(nums[right]==0 && zeroCount==k+1){
//更新左边界
if(nums[left]==0)
zeroCount--;
left++;
}
//该收结果了
res = Math.max(res,right-left+1);
right++;
}
return res;
}
}
二、替换后的最长重复字符(力扣424)********较难(多复习)
分析:
和一般的滑动窗口有一些不同,记录窗口内出现的字符数目,用count来记录窗口内出现次数最多的字符个数,最重要的 当right - left > count + k 时,此时left指针需要进行右移,对应的count[s.charAt(left)-‘A’ ]也要减减,最后更新结果即可
class Solution {
public int characterReplacement(String s, int k) {
int len = s.length();
if(len<2) return len;
//最大滑动窗口
int left = 0;
int right = 0;
int count = 0;
int res = 0;
int[] freq = new int[26];
while(right<s.length()){
char c = s.charAt(right);
freq[c-'A']++;
count = Math.max(count,freq[c-'A']);
right++;
if(right-left>count+k){
freq[s.charAt(left)-'A']--;
left++;
}
res = Math.max(res,right-left);
}
return res;
}
}
三、尽可能使字符串相等(力扣1208)
分析:
比较简单的滑动窗口,注意在求差值时要加绝对值
class Solution {
public int equalSubstring(String s, String t, int maxCost) {
//最大滑动窗口问题
int left = 0;
int right =0;
int[] diff = new int[s.length()];
for(int i=0;i<s.length();i++){
diff[i] = Math.abs(t.charAt(i)-s.charAt(i));
}
int temp= 0;
int res = 0;
while(right<s.length()){
temp += diff[right];
while(temp>maxCost){ //不满足条件的情况下
temp-=diff[left];
left++;
}
//更新结果
res = Math.max(res,right-left+1);
right++;
}
return res;
}
}
四、无重复字符的最长子串(力扣3)
分析:
正常滑动窗口
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
if(s==null || s=="" ||n==1){
return 1;
}
int left = 0;
int right = 0;
int res = 0;
Map<Character,Integer> map = new HashMap<>();
while(right<s.length()){
map.put(s.charAt(right),map.getOrDefault(s.charAt(right),0)+1);
while(map.get(s.charAt(right))>1){ //条件不满足
//此时需要更新左边界
map.put(s.charAt(left),map.get(s.charAt(left))-1);
left ++;
}
res = Math.max(res,right-left+1);
right++;
}
return res;
}
}
五、长度最小的子数组(力扣209)
分析:
常规滑动窗口问题
class Solution {
public int minSubArrayLen(int target, int[] nums) {
//最小滑动窗口
int left = 0;
int right = 0;
int res = Integer.MAX_VALUE;
int count = target;
while(right<nums.length){
count -=nums[right];
//当满足条件时
while(count<=0){
//收集结果
res = Math.min(res,right-left+1);
//缩小左边界
count += nums[left];
left++;
}
right++;
}
return res==Integer.MAX_VALUE? 0:res;
}
}
六、乘积小于 K 的子数组(力扣713)
分析:
由题意,注意 单独处理 k=1和 k=0的情况
if(k<=1) return 0;
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int left =0 ;
int right = 0;
int res = 0;
int temp = 1;
if(k<=1) return 0;
while(right<nums.length){
temp *= nums[right];
while(temp>=k){ //不满足条件
temp/=nums[left];
left++;
}
//在外更新结果
res +=(right-left+1);
right++;
}
return res;
}
}