【LeetCode:76. 最小覆盖子串 | 滑动窗口】-LMLPHP

【LeetCode:76. 最小覆盖子串 | 滑动窗口】-LMLPHP

【LeetCode:76. 最小覆盖子串 | 滑动窗口】-LMLPHP

🚩 题目链接

⛲ 题目描述

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

注意:

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

示例 1:

输入:s = “ADOBECODEBANC”, t = “ABC”
输出:“BANC”
解释:最小覆盖子串 “BANC” 包含来自字符串 t 的 ‘A’、‘B’ 和 ‘C’。
示例 2:

输入:s = “a”, t = “a”
输出:“a”
解释:整个字符串 s 是最小覆盖子串。
示例 3:

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

提示:

m == s.length
n == t.length
1 <= m, n <= 105
s 和 t 由英文字母组成

🌟 求解思路&实现代码&运行结果


⚡ 滑动窗口

🥦 求解思路
  1. 该题目我们通过滑动窗口来求解,同时,该题目需要维护俩个字符串的词频表(s是变化的,t是固定的),然后右指针不断向右移动,每次判断s是否覆盖t(通过维护的词频表来判断),如果可以,那么判断是否满足长度最短,如果最短,更新并记录答案,如果不是最短,继续判断,此时,左指针右移,缩小窗口,继续后续的过程。
  2. 实现代码如下所示:
🥦 实现代码
class Solution {

    public String minWindow(String s, String t) {
        int max = s.length();
        String ans = "";
        int left = 0;
        int n = s.length();
        int[] cnt = new int[128];
        int[] cnt1 = new int[128];
        for (char c : t.toCharArray()) {
            cnt1[c]++;
        }
        for (int right = 0; right < n; right++) {
            char c = s.charAt(right);
            cnt[c]++;
            while (check(cnt, cnt1)) {
                if (right - left + 1 <= max) {
                    max = right - left + 1;
                    ans = s.substring(left, right + 1);
                }
                cnt[s.charAt(left++)]--;
            }
        }
        return ans;
    }

    public boolean check(int[] cnt, int[] cnt1) {
        for (int i = 0; i < cnt1.length; i++) {
            if (cnt1[i] > cnt[i])
                return false;
        }
        return true;
    }
}
🥦 运行结果

【LeetCode:76. 最小覆盖子串 | 滑动窗口】-LMLPHP


💬 共勉

【LeetCode:76. 最小覆盖子串 | 滑动窗口】-LMLPHP

【LeetCode:76. 最小覆盖子串 | 滑动窗口】-LMLPHP

01-14 01:45