76最小覆盖子串

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

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

示例 1:

输入:s = "ADOBECODEBANC", t = "ABC"
输出:"BANC"

示例 2:

输入:s = "a", t = "a"
输出:"a"

提示:

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

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/minimum-window-substring 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution 1

滑动窗口

import java.util.*;

class Solution {
    public String minWindow(String s, String t) {
        int start = 0, end = 0, minLen = Integer.MAX_VALUE;
        int i = 0, j = 0;
        Map<Character, Integer> dict = new HashMap<>(128);
        int missingCharNum = t.length();
        if (missingCharNum == 0)
            return new String("");
        // construct dict, which is a counter for char in t
        for (int index = 0; index < t.length(); index++) {
            Character key = t.charAt(index);
            if (dict.containsKey(key))
                dict.replace(key, dict.get(key) + 1);
            else
                dict.put(key, 1);
        }
        // slide windows
        while (j < s.length()) {
            // j++
            while (missingCharNum > 0 && j < s.length()) {
                Character key = s.charAt(j++);
                if (dict.containsKey(key)) {
                    dict.replace(key, dict.get(key) - 1);
                    if (dict.get(key) >= 0)
                        missingCharNum--;
                }
            }
            // i++
            while (missingCharNum == 0 && i < j) {
                if (j - i < minLen) {
                    minLen = j - i;
                    start = i;
                    end = j;
                }
                Character key = s.charAt(i++);
                if (dict.containsKey(key)) {
                    dict.replace(key, dict.get(key) + 1);
                    if (dict.get(key) > 0)
                        missingCharNum++;
                }
            }
        }
        return s.substring(start, end);
    }
}