Thursday, December 25, 2014

Minimum Window Substring (LeetCode HashMap)

Question: 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 empty string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

Idea: Use two pointers to keep a sliding window. If the window does not contain T, move the right boundary forward. If the window contains T, keep moving the left boundary forward until the window no longer contains T. The loop ends when the right boundary of the window reaches the right boundary of S and the window does not contain T. Update the minimum window size whenever a new valid (containing T) window is visited.

Time: O(n)  Space: O(n)

Code:
 public class Solution {  
   public String minWindow(String S, String T) {  
     if(S.length()==0||T.length()==0)  
     {  
       return "";  
     }  
     HashMap<Character,Integer> toFind=new HashMap<Character,Integer>();  
     for(int i=0;i<T.length();i++)  
     {  
       char c=T.charAt(i);  
       if(toFind.containsKey(c))  
       {  
         toFind.put(c,toFind.get(c)+1);  
       }  
       else  
       {  
         toFind.put(c,1);  
       }  
     }  
     HashMap<Character,Integer> found=new HashMap<Character,Integer>();  
     int leftBound=0;  
     int counter=0;  
     String result="";  
     for(int i=0;i<S.length();i++)  
     {  
       char c=S.charAt(i);  
       if(!toFind.containsKey(c))  
       {  
         continue;  
       }  
       if(found.containsKey(c))  
       {  
         found.put(c,found.get(c)+1);  
       }  
       else  
       {  
         found.put(c,1);  
       }  
       if(found.get(c)<=toFind.get(c))  
       {  
         counter++;  
       }  
       if(counter==T.length())  
       {  
         while(leftBound<S.length())  
         {  
           char left=S.charAt(leftBound);  
           if(!toFind.containsKey(left))  
           {  
             leftBound++;  
             continue;  
           }  
           if(found.get(left)>toFind.get(left))  
           {  
             found.put(left,found.get(left)-1);  
             leftBound++;  
             continue;  
           }  
           break;  
         }  
         if(result.equals("")||result.length()>i-leftBound+1)  
         {  
           result=S.substring(leftBound,i+1);  
         }  
       }  
     }  
     return result;  
   }  
 }  


No comments:

Post a Comment