题解 | #最小覆盖子串#
最小覆盖子串
https://www.nowcoder.com/practice/c466d480d20c4c7c9d322d12ca7955ac
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 滑动窗口,用map维护窗口大小 * * @param S string字符串 * @param T string字符串 * @return string字符串 */ public String minWindow(String str, String target) { Map<Character, Integer> map = new HashMap<>(); for (char charAt : target.toCharArray()) { map.put(charAt, map.getOrDefault(charAt, 0) + 1); } int left = 0, right = 0, start = 0, window = Integer.MAX_VALUE; while (right < str.length()) { char rightCh = str.charAt(right); if (map.containsKey(rightCh)) { map.put(rightCh, map.get(rightCh) - 1); } while (judge(map)) { if (right - left + 1 < window) { window = right - left + 1; start = left; } char leftCh = str.charAt(left++); if (map.containsKey(leftCh)) { map.put(leftCh, map.get(leftCh) + 1); } } right++; } return window == Integer.MAX_VALUE ? "" : str.substring(start, start + window ); } boolean judge(Map<Character, Integer> map) { for (Map.Entry<Character, Integer> entry : map.entrySet()) { if (entry.getValue() > 0) { return false; } } return true; } }