Sunday, February 9, 2014

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.
// O(N) -> hash table
public class Solution {
    public String minWindow(String S, String T) {
        if(S == null || T == null || S.length() == 0 || T.length() == 0){
            return "";
        }
        int[] needToFind = new int[256];  // hash table 
        int[] hasFound = new int[256];
        for(int i = 0; i < T.length(); i++){
            needToFind[T.charAt(i)]++;
        }
        
        int count = 0; // size of "valid" elements found so far.
        int begin = 0;
        int minLen = Integer.MAX_VALUE, minBeg = 0, minEnd = 0;
        for(int i = 0; i < S.length(); i++){
            if(needToFind[S.charAt(i)] == 0){ 
                continue;
            }
            hasFound[S.charAt(i)]++;
            if(hasFound[S.charAt(i)] <= needToFind[S.charAt(i)]) count++;
            if(count == T.length()){
                while(needToFind[S.charAt(begin)] == 0 || 
                      hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)]){ // always keep the restrcition
                          if(hasFound[S.charAt(begin)] > needToFind[S.charAt(begin)]){
                              hasFound[S.charAt(begin)]--;
                          }
                          begin++;
                      }
                int len = i - begin + 1;
                if(len < minLen){
                    minLen = len;
                    minBeg = begin;
                    minEnd = i;
                }
            }
        }
        
        if(count == T.length()){
            return S.substring(minBeg, minEnd + 1);
        }
        return "";
    }
}

No comments:

Post a Comment