1.题目

给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。

注意:
对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
如果 s 中存在这样的子串,我们保证它是唯一的答案。

示例 1:
输入:s = “ADOBECODEBANC”, t = “ABC”
输出:“BANC”

示例 2:
输入:s = “a”, t = “a”
输出:“a”

示例 3:
输入: s = “a”, t = “aa”
输出: “”
解释: t 中两个字符 ‘a’ 均应包含在 s 的子串中,
因此没有符合条件的子字符串,返回空字符串。

提示:
1 <= s.length, t.length <= 105
s 和 t 由英文字母组成

进阶:你能设计一个在 O(n) 时间内解决此问题的算法吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-window-substring

2.思路

(1)滑动窗口
参考链接:我写了套框架,把滑动窗口算法变成了默写题。

相关题目:
LeetCode_滑动窗口_中等_438.找到字符串中所有字母异位词

3.代码实现(Java)

//思路1————滑动窗口
class Solution {
    public String minWindow(String s, String t) {
        int sLen = s.length();
        int tLen = t.length();
        if (sLen < tLen) {
            return "";
        }
        Map<Character, Integer> window = new HashMap<>();
        Map<Character, Integer> target = new HashMap<>();
        //将字符串 t 中的字符存入哈希表 target 中,key/value 为字符/对应出现的次数
        for (int i = 0; i < tLen; i++) {
            char c = t.charAt(i);
            target.put(c, target.getOrDefault(c, 0) + 1);
        }
        int left = 0;
        int right = 0;
        int valid = 0;
        //记录最小覆盖子串的起始索引以及长度
        int start = 0;
        int minLen = Integer.MAX_VALUE;
        while (right < sLen) {
            char inC = s.charAt(right++);
            if (target.containsKey(inC)) {
                window.put(inC, window.getOrDefault(inC, 0) + 1);
                if (window.get(inC).equals(target.get(inC))) {
                    valid++;
                }
            }
            //窗口收缩的条件
            while (valid == target.size()) {
                if (minLen > right - left) {
                    start = left;
                    minLen = right - left;
                }
                char outC = s.charAt(left++);
                if (target.containsKey(outC)) {
                    if (window.get(outC).equals(target.get(outC))) {
                        valid--;
                    }
                    window.put(outC, window.get(outC) - 1);
                }
            }
        }
        return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
    }
}

更多推荐