Wednesday, April 9, 2014

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.

Solution:

We first preprocess T to obtain an array with the number of apperarances of each character, then we traverse S keeping the minimum window that contains all the letters of T.

public class Solution {
    public String minWindow(String S, String T) {
        int[] tProcessed = new int['z'-'A'+1];
        for(int i=0; i<T.length();i++)
            tProcessed[T.charAt(i)-'A']++;
        int begin = 0;
        int lettersFound = 0;
        int end = 0;
        int minWindow = Integer.MAX_VALUE;
        int startMinWindow = -1;
        int[] window = new int['z'-'A'+1];
        while(end<S.length())
        {
            window[S.charAt(end)-'A']++;
            if (window[S.charAt(end)-'A']<=tProcessed[S.charAt(end)-'A'])
                lettersFound++;
            if (lettersFound>=T.length())
            {
                while(window[S.charAt(begin)-'A']>tProcessed[S.charAt(begin)-'A'])
                {
                    window[S.charAt(begin)-'A']--;
                    begin++;
                }
                if(end+1-begin<minWindow)
                {
                    startMinWindow = begin;
                    minWindow = end+1-begin;
                }
            }
            end++;
        }
        if (startMinWindow == -1)
            return "";
        return S.substring(startMinWindow,startMinWindow+minWindow);
    }
}

No comments :

Post a Comment