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
| class Solution { public String minWindow(String s, String t) { Map<Character, Integer> need = new HashMap<>(); Map<Character, Integer> window = new HashMap<>();
for (int i = 0; i < t.length(); i++){ need.put(t.charAt(i), need.getOrDefault(t.charAt(i), 0) + 1); }
int left = 0; int right = 0; int start = 0; int valid = 0; int len = Integer.MAX_VALUE; while (right < s.length()){ char c = s.charAt(right); right++; if (need.containsKey(c)){ window.put(c, window.getOrDefault(c, 0) + 1); if (window.get(c).equals(need.get(c))){ valid++; } }
while(valid == need.size()){ if (right - left < len){ start = left; len = right - left; }
char d = s.charAt(left); left++; if (need.containsKey(d)){ if (window.get(d).equals(need.get(d))){ valid--; } window.put(d, window.get(d) - 1); } } } return len == Integer.MAX_VALUE ? "" : s.substring(start, start+len); } }
|