Problem 76: Minimum Window Substring

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

思路

复杂度

  • Time: O(n)

public class Solution {
    public String minWindow(String s, String t) {
        int[] map = new int[128];
        for (char c : t.toCharArray()) {
            map[c]++;
        }

        int i = 0, j = 0, start = 0;
        int count = t.length(), minLen = Integer.MAX_VALUE;
        while (j < s.length()) {
            if (map[s.charAt(j++)]-- > 0) count--;
            while (count == 0) { // valid
                if (j - i < minLen) {
                    minLen = j - i;
                    start = i;
                }
                if (map[s.charAt(i++)]++ == 0) count++; 
            }
        }

        return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
    }
}

易错点

  1. 关键语句的解读

    if (map[s.charAt(j++)]-- > 0)

    这里实际上是,

    if (map[s.charAt(j)] > 0) {...}
    map[s.charAt(j)]--;
    j++;

Last updated