|
| 1 | +package String; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * @author tujietg |
| 8 | + * @date 5/23/20 1:03 PM |
| 9 | + */ |
| 10 | +public class No76 { |
| 11 | + public static String minWindow(String s, String t) { |
| 12 | + int sLen = s.length(); |
| 13 | + |
| 14 | + int start = -1; |
| 15 | + int end = sLen - 1; |
| 16 | + |
| 17 | + char[] tChars = t.toCharArray(); |
| 18 | + char[] sChars = s.toCharArray(); |
| 19 | + |
| 20 | + if (s.length() < t.length()) { |
| 21 | + return ""; |
| 22 | + } |
| 23 | + |
| 24 | + Map<Character, Integer> tMap = new HashMap<>(t.length()); |
| 25 | + |
| 26 | + for (int i = 0; i < tChars.length; i++) { |
| 27 | + tMap.put(tChars[i], tMap.getOrDefault(tChars[i], 0) + 1); |
| 28 | + } |
| 29 | + |
| 30 | + for (int i = 0; i < sLen; i++) { |
| 31 | + for (int j = i; j < sLen; j++) { |
| 32 | + String substring = s.substring(i, j + 1); |
| 33 | + HashMap<Character, Integer> characterIntegerHashMap = new HashMap<>(t.length()); |
| 34 | + characterIntegerHashMap.putAll(tMap); |
| 35 | + if (check(characterIntegerHashMap, substring.toCharArray()) == true) { |
| 36 | + if (j - i <= end - start) { |
| 37 | + end = j; |
| 38 | + start = i; |
| 39 | + j = sLen; |
| 40 | + while (!tMap.containsKey(sChars[i]) && i < sLen && !tMap.containsKey(sChars[i + 1])) { |
| 41 | + i++; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return start == -1 ? "" : s.substring(start, end + 1); |
| 48 | + } |
| 49 | + |
| 50 | + private static boolean check(Map<Character, Integer> midMap, char[] sChars) { |
| 51 | + for (int i = 0; i < sChars.length; i++) { |
| 52 | + if (midMap.containsKey(sChars[i])) { |
| 53 | + if (midMap.get(sChars[i]).equals(1)) { |
| 54 | + midMap.remove(sChars[i]); |
| 55 | + } else { |
| 56 | + midMap.put(sChars[i], midMap.get(sChars[i]) - 1); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + return midMap.size() == 0; |
| 61 | + } |
| 62 | +} |
0 commit comments