题目
https://leetcode-cn.com/problems/minimum-window-substring/
解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class Solution { public String minWindow(String s, String t) { if (s == null) { return ""; }
Map<Character, Integer> needs = new HashMap<>(); Map<Character, Integer> windows = new HashMap<>();
for (int i = 0; i < t.length(); i++) { char c = t.charAt(i); needs.put(c, needs.getOrDefault(c, 0)+1); } int left = 0, right = 0; int count = 0; int minLen = Integer.MAX_VALUE; int start=0,end=0; while (right < s.length()) { char temp = s.charAt(right); if (needs.containsKey(temp)) { windows.put(temp, windows.getOrDefault(temp, 0)+1); if (windows.get(temp).equals(needs.get(temp))) { count++; } } right++; while(count == needs.size()) { if (right-left<minLen) { start = left; end = right; minLen = end - start; } char c = s.charAt(left); if (needs.containsKey(c)) { windows.put(c, windows.getOrDefault(c, 1)-1); if (windows.get(c) < needs.get(c)) { count--; } } left++; } } return minLen==Integer.MAX_VALUE ?"":s.substring(start, end); } }
|