滑动窗口Sliding Window Algorithm
Posted nevergiveup0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了滑动窗口Sliding Window Algorithm相关的知识,希望对你有一定的参考价值。
应用及优点:
1.可用于解决数组或者字符串的子元素问题。
2.用单循环代替了嵌套循环问题,时间复杂度低。
3.用双指针维护动态窗口。
相关算法题:
Longest Substring Without Repeating Characters无重复最长子串
Find All Anagrams in a String(找到字符串中所有字母异位词)
Minimum Window Substring最小覆盖子串
209. Minimum Size Subarray Sum长度最小子数组
以“Find All Anagrams in a String”为例:
Given a string s and a non-empty string p, find all the start indices of p‘s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.The order of output does not matter.
Example 1:
Input: s: "cbaebabacd" p: "abc" Output: [0, 6]
class Solution { public List<Integer> findAnagrams(String s, String p) { int [] need=new int[128]; int [] win=new int[128]; int left=0;int right=0; List<Integer> res=new ArrayList<>(); for(int i=0;i<p.length();i++){ need[p.charAt(i)]++;//将目标数组中各元素计数。 } while(right<s.length()){ win[s.charAt(right)]++;//窗口右移 while(right<s.length()&&win[s.charAt(right)]>need[s.charAt(right)]){//窗口停止右移条件 win[s.charAt(left)]--; left+;//窗口左移 } if(right-left+1==p.length()){ res.add(left); } right++; } return res; } }
以上是关于滑动窗口Sliding Window Algorithm的主要内容,如果未能解决你的问题,请参考以下文章
POJ - 2823 Sliding Window (滑动窗口入门)
LeetCode 239. Sliding Window Maximum(滑动窗口最大值)