滑動視窗問題的實現
阿新 • • 發佈:2021-01-07
滑動視窗的模板
int left = 0, right = 0;
while (right < s.size()) {`
// 增大視窗
window.add(s[right]);
right++;
while (window needs shrink) {
// 縮小視窗
window.remove(s[left]);
left++;
}
}
例項
- Leetcode 3 無重複字元的最長子串長度
class Solution { public int lengthOfLongestSubstring(String s) { if(s.length() == 0 ){ return 0 ; } HashMap<Character,Integer> map= new HashMap<Character,Integer>(); int max =0; int left = 0 ; for(int i = 0 ;i< s.length(); ++i){ if(map.containsKey(s.charAt(i))){ left = Math.max(left,map.get(s.charAt(i))+1); } map.put(s.charAt(i),i); max=Math.max(max,i-left+1); } return max ; } }
- LeetCode 76 最小覆蓋子串
class Solution { public static String minWindow(String s, String t) { if (s == null || s == "" || t == null || t == "" || s.length() < t.length()) { return ""; } //用來統計t中每個字元出現次數 int[] needs = new int[128]; //用來統計滑動視窗中每個字元出現次數 int[] window = new int[128]; for (int i = 0; i < t.length(); i++) { needs[t.charAt(i)]++; } int left = 0; int right = 0; String res = ""; //目前有多少個字元 int count = 0; //用來記錄最短需要多少個字元。 int minLength = s.length() + 1; while (right < s.length()) { char ch = s.charAt(right); window[ch]++; if (needs[ch] > 0 && needs[ch] >= window[ch]) { count++; } //移動到不滿足條件為止 while (count == t.length()) { ch = s.charAt(left); if (needs[ch] > 0 && needs[ch] >= window[ch]) { count--; } if (right - left + 1 < minLength) { minLength = right - left + 1; res = s.substring(left, right + 1); } window[ch]--; left++; } right++; } return res; } }