leetcode

Minimum Window Substring

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.

For String S = "ADOBECODEBANC", String T = "ABC".

We first find ADOBEC which contains all ABC.

Then when we see the second B, do not stop because we haven't seen A yet.

Then we see the second A, we can move start pointer to C, so "CODEBA" but length is longer than ADOBEC,

Then when we see the second C, we can move start pointer to B, since "BANC" also contains all ABC and is shorter than ADOBEC.

public String minWindow(String S, String T) {
        if (S==null||T==null) {
            return null;
        }

        if ((S.isEmpty()&&T.isEmpty())|| S.length()<T.length()) {
            return "";
        }

        Map<Character, Integer> dict = new HashMap<Character, Integer>();
        Map<Character, Integer> found = new HashMap<Character, Integer>();

        for(int i=0; i<T.length(); i++){
            found.put(T.charAt(i), 0);

            if (dict.containsKey(T.charAt(i))){
                dict.put(T.charAt(i), dict.get(T.charAt(i))+1);
            }
            else{
                dict.put(T.charAt(i), 1);

            }
        }

        int start = 0;
        int end = 0;
        int totalCharsFound = 0;
        int minLength = Integer.MAX_VALUE;
        String result = "";

        while (end<S.length()) {
            char c = S.charAt(end);
            //put all found chars in the map
            if (found.containsKey(c)) {
                if (found.get(c)<dict.get(c)) {
                    totalCharsFound = totalCharsFound + 1;
                }
                found.put(c, found.get(c)+1);

                //all chars found
                if (totalCharsFound==T.length()) {
                    char sc = S.charAt(start);
                    //ignore not needed chars and remove additional needed chars
                    while (!found.containsKey(sc)||found.get(sc)>dict.get(sc)) {
                        if (found.containsKey(sc)) {
                            found.put(sc, found.get(sc)-1);
                        }
                        start = start + 1;
                        sc = S.charAt(start);
                    }
                    int length = end-start+1;
                    if (length<minLength) {
                        result = S.substring(start, end+1);
                        minLength = length;
                    }
                }
            }    
            end = end+1;
        }

        return result;
    }