已知数组或字符串,求符合要求的子数组或子串,通常采用滑动窗口,在力扣看到一篇很好的总结,分享下:
滑动窗口的套路:窗口的左右边界r,l从0开始,先移动r,达到需求后,改为移动l,直到再次不符合需求,然后再移动r...以此类推,直到r超过数组长度,程序结束。
链接中,以C语言实现为主,均为已知字符串找子串的例子。下面用JAVA挑两题实现一下,下面两题用了相同的模板,变的只有需求,整体大同小异。
76. 最小覆盖子串
public static String minWindow(String s, String t) {
Map<Character, Integer> need = new HashMap<>();
Map<Character, Integer> window = new HashMap<>();
int len = t.length();
for (int i = 0; i < len; i++) {
Character c = t.charAt(i);
need.put(c, need.getOrDefault(c, 0) + 1);
window.put(c, 0);
}
int l = 0, r = 0;
int minWindow = Integer.MAX_VALUE;
String ans = "";
//while限制窗口右侧
while (r < s.length()) {
Character rc = s.charAt(r);
if (need.containsKey(rc)) {
int currCount = window.get(rc);
window.put(rc, currCount + 1);
//判断是否超过了所需,如果超过了就不减了,
//如需要AABC,窗口中此时是AAA,len只减2,超过2就不减了
if (currCount + 1 <= need.get(rc))
len--;
}
//window中内容已经满足要求,开始移动窗口左侧,
//直到移动到再次不符合要求停止
while (len == 0) {
if (r - l + 1 < minWindow) {
minWindow = r - l + 1;
ans = s.substring(l, r + 1);
}
Character lc = s.charAt(l);
if (need.containsKey(lc)) {
int currCount = window.get(lc);
window.put(lc, currCount - 1);
if (currCount - 1 < need.get(lc))
len++;
}
l++;
}
r++;
}
return ans;
}
567. 字符串的排列
public static boolean checkInclusion(String s1, String s2) {
Map<Character, Integer> need = new HashMap<>();
Map<Character, Integer> window = new HashMap<>();
int len = s1.length();
for (int i = 0; i < len; i++) {
Character c = s1.charAt(i);
need.put(c, need.getOrDefault(c, 0) + 1);
window.put(c, 0);
}
int r = 0, l = 0;
while (r < s2.length()) {
Character rc = s2.charAt(r);
if (need.containsKey(rc)) {
int currCount = window.get(rc);
window.put(rc, currCount + 1);
if (currCount + 1 <= need.get(rc)) {
len--;
}
}
while (len == 0) {
if (r - l + 1 == s1.length())
return true;
Character lc = s2.charAt(l);
if (need.containsKey(lc)) {
int currCount = window.get(lc);
window.put(lc, currCount - 1);
if (currCount - 1 < need.get(lc)) {
len++;
}
}
l++;
}
r++;
}
return false;
}
下面整理两题数组的滑动窗口应用,比起字符串更加简单,滑动窗口的套路不变。
713. 乘积小于 K 的子数组
此题只要知道子数组怎么在滑动窗口移动时计数即可,如窗口是[1](符合需求),则此时计数为1(子数组为[1],为窗口长度);移动右边界,窗口变为[1,2](符合需求),则此时计数为1+2(增加子数组[2]和[1,2],即增加窗口长度2);继续移动右边界,窗口变为[1,2,3](不符合需求),不计数,移动左边界,窗口变为[2,3](符合需求),则此时计数为1+2+2(增加子数组[3]和[2,3]),以此类推...
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
int count=0;
int l=0,r=0;
long sum=1;
while(r<nums.length){
sum*=nums[r];
while(sum>=k&&l<=r){
sum/=nums[l];
l++;
}
if(sum<k)
count+=r-l+1;
r++;
}
return count;
}
}
209. 长度最小的子数组
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int l=0,r=0;
long sum=0;
int minLen=Integer.MAX_VALUE;
while(r<nums.length){
sum+=nums[r];
while(sum>=target){
minLen=Math.min(minLen,r-l+1);
sum-=nums[l];
l++;
}
r++;
}
//不存在符合条件的子数组
if(minLen==Integer.MAX_VALUE)
minLen=0;
return minLen;
}
}