Minimum Window Substring

update Mar 5, 2021

Given two strings source and target. Return the minimum substring of source which contains each char of target. Example

Example 1:

Input: source = "abc", target = "ac"
Output: "abc"

Example 2:

Input: source = "adobecodebanc", target = "abc"
Output: "banc"
Explanation: "banc" is the minimum substring of source string which contains each char of target "abc".

Example 3:

Input: source = "abc", target = "aa"
Output: ""
Explanation: No substring contains two 'a'.

Challenge

O(n) time

Notice

    If there is no answer, return "".
    You are guaranteed that the answer is unique.
    target may contain duplicate char, while the answer need to contain at least the same number of that char.

Basic Idea

要找到source中包含target中全部字符(需要重复次数相同)的最短substring,我们以先用一个map统计target中每个字符出现的次数,然后利用双指针, 保证每次循环中先前进右边界,找到当前满足条件的窗口,然后逐渐右移左边界,这样就可以找到左右满足条件的窗口。

Java Code

Last updated