题解 | #牛群名字覆盖#
牛群名字覆盖
https://www.nowcoder.com/practice/e6cef4702e7841f59cf47daf9bafb241
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param t string字符串 * @return string字符串 */ public String minWindow (String s, String t) { // write code here Map<Character, Integer> m = new HashMap<>(); for (int i = 0; i < t.length(); i++) { m.put(t.charAt(i), m.getOrDefault(t.charAt(i), 0) - 1); } int slow = 0, fast = 0; int left = -1, right = -1; int cnt = s.length() + 1; while (fast < s.length()) { char c = s.charAt(fast); if (m.containsKey(c)) { m.put(c, m.get(c) + 1); } while (check(m)) { if (cnt > fast - slow + 1) { cnt = fast - slow + 1; left = slow; right = fast; } char ch = s.charAt(slow); if (m.containsKey(ch)) { m.put(ch, m.get(ch) - 1); } slow++; } fast++; } if (left == -1) { return ""; } return s.substring(left, right + 1); } private boolean check(Map<Character, Integer> m) { for (Integer value : m.values()) { if (value < 0) { return false; } } return true; } }
知识点 : 滑动窗口
题目解答分析:
- 定义一个指针left来表示当前窗口的左端点,然后从左往右遍历整个字符串,可以使用哈希表need来记录指定英文字母出现的次数,使用哈希表cnt来记录窗口内各个字符出现的次数依次将每个字符加入窗口中:
- 如果当前窗口包含了所有指定英文字母,则更新答案并尝试将窗口左端点向右移动;
- 重复以上步骤 直到窗口不能再向右移动。