滑动窗口 + 哈希表 解决最小覆盖子串问题
public class Code_76 {public String minWindow(String s, String t) {int ansLeft = -1;int m = s.length();int ansRight = m;Map<Character, Integer> cntT = new HashMap<>(); for (char c : t.toCharArray()) {cntT.put(c, cntT.getOrDefault(c, 0) + 1);}Map<Character, Integer> cntS = new HashMap<>(); int left = 0;int formed = 0; int required = cntT.size(); for(int right=0; right<m; right++) {char sr = s.charAt(right);cntS.put(sr, cntS.getOrDefault(sr, 0) + 1);if(cntT.containsKey(sr) && cntS.get(sr).intValue() == cntT.get(sr).intValue()) {formed++;}while (formed == required) {if (right - left < ansRight - ansLeft) {ansLeft = left;ansRight = right;}char leftChar = s.charAt(left);cntS.put(leftChar, cntS.get(leftChar) - 1);if (cntT.containsKey(leftChar) && cntS.get(leftChar) < cntT.get(leftChar)) {formed--;}left++;}}return ansLeft < 0 ? "" : s.substring(ansLeft, ansRight+1); }public static void main(String[] args) {Code_76 test = new Code_76();String s = test.minWindow("ADOBECODEBANC", "ABC");System.out.println(s);}
}
同样的解题思路,还有水果成篮问题:
public class Code_904 {public int totalFruit(int[] fruits) {int n = fruits.length;int i, j=0, ans=0;Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();for(i=0; i<n; i++) {cnt.put(fruits[i], cnt.getOrDefault(fruits[i],0) + 1);while(cnt.size() > 2) {cnt.put(fruits[j], cnt.get(fruits[j]) - 1);if(cnt.get(fruits[j]) == 0) {cnt.remove(fruits[j]);}j++;}ans = Math.max(ans, i-j+1);}return ans;}public static void main(String[] args) {Code_904 test = new Code_904();int[] fruits = new int[]{3,3,3,1,2,1,1,2,3,3,4};int ans = test.totalFruit(fruits);System.out.println(ans);}
}