首页 > 代码库 > 最小覆盖子串

最小覆盖子串

题目

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.
Note:
If there is no such window in S that covers all characters in T, return the emtpy string ““.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

思路

我的思路倒是和正确的思路是一样的

双指针思想,尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的

但是为什么这个想法是对的呢?

另外注意一下自己的那个contains方法,如果是全扫的话容易超时,LeetOJ明显不是按复杂度来算的。

代码

public class Solution {
    Map<Character, Integer> map = new HashMap<Character, Integer>();

    public String minWindow(String S, String T) {
        int i = 0;
        int j = 0;

        int[] count = new int[128];
        int minWindows = Integer.MAX_VALUE;
        String minWindowString="";

        for (char c : T.toCharArray()) {
            if (!map.containsKey(c)) {
                map.put(c, 0);
            }
            map.put(c, map.get(c) + 1);
        }

        for (; j < S.length(); j++) {
            if (contain(count, T)) {
                for (; i <= j; i++) {
                    if (!contain(count, T)) {
                        break;
                    } else {
                        if(minWindows > j-i) {
                            minWindows = j-i;
                            minWindowString = S.substring(i,j);
                        }

                    }
                    // contains i in this iteration
                    count[S.charAt(i)]--;
                }
            }
            // do not contains j in this iteration
            count[S.charAt(j)]++;
        }

        for (; i < j; i++) {
            if (!contain(count, T)) {
                break;
            } else {
                if(minWindows > j-i) {
                    minWindows = j-i;
                    minWindowString = S.substring(i,j);
                }
            }
            count[S.charAt(i)]--;
        }

        // System.out.println(minWindowString);
        if (i == 0) {
            return "";
        }
        return minWindowString;
    }

    private boolean contain(int[] count, String t) {
        for (char character : map.keySet()) {
            if (count[character] < map.get(character)) {
                return false;
            }
        }
        return true;
    }
}

最小覆盖子串