0
点赞
收藏
分享

微信扫一扫

Day41 最小覆盖子串

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

https://leetcode-cn.com/problems/minimum-window-substring/

注意:如果 s 中存在这样的子串,我们保证它是唯一的答案。

示例1:

示例2:

提示:

Java解法

package sj.shimmer.algorithm.m2;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by SJ on 2021/3/6.
 */


class D41 {
    public static void main(String[] args) {
//        System.out.println(minWindow("ADOBECODEBANC", "ABC"));
        System.out.println(minWindow("a", "a"));
    }

    static Map<Character, Integer> tCharNum = new HashMap<>();
    static Map<Character, Integer> mCharNum = new HashMap<>();

    public static String minWindow(String s, String t) {

        String matchS = "";

        if (s == null || s.equals("") || t == null || t.equals("")) {
            return matchS;
        }
        int tLength = t.length();
        int sLength = s.length();
        for (int i = 0; i < tLength; i++) {
            char key = t.charAt(i);
            tCharNum.put(key, tCharNum.getOrDefault(key, 0) + 1);
        }
        int resultLeft = -1;
        int resultRight = -1;
        int resultLength = Integer.MAX_VALUE;
        int left = 0;
        int right = -1;
        while (right < sLength) {
            right++;
            if (right < sLength && tCharNum.containsKey(s.charAt(right))) {
                mCharNum.put(s.charAt(right), mCharNum.getOrDefault(s.charAt(right), 0) + 1);
            }
            while (left <= right && checkIn()) {
                if (right - left + 1 < resultLength) {//记录最短长度
                    resultLength = right - left + 1;
                    resultLeft = left;
                    resultRight = left + resultLength;//拼接时需要增加一位
                }
                if (tCharNum.containsKey(s.charAt(left))) {
                    mCharNum.put(s.charAt(left), mCharNum.getOrDefault(s.charAt(left), 0) - 1);
                }
                left++;
            }
        }
        matchS = resultLeft == -1 ? "" : s.substring(resultLeft, resultRight);
        return matchS;
    }

    private static boolean checkIn() {
        for (Map.Entry<Character, Integer> entry : tCharNum.entrySet()) {
            if (entry.getValue() > mCharNum.getOrDefault(entry.getKey(), 0)) {
                return false;
            }
        }
        return true;
    }
}

官方解

https://leetcode-cn.com/problems/minimum-window-substring/solution/zui-xiao-fu-gai-zi-chuan-by-leetcode-solution/

  1. 滑动窗口

    • 时间复杂度:O(C⋅∣s∣+∣t∣)

    • 空间复杂度: O(C) ,设字符集大小为 C

举报

相关推荐

0 条评论