Tuesday, December 23, 2014

Substring with Concatenation of All Words (LeetCode HashMap)

Question:You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

Idea: Brute force. Start from each character in S,  check whether the substring with "L.length*L[0].length" length is a valid concatenation.

Time: O(n^2). Space: O(n).

Code: 
 public class Solution {  
   public List<Integer> findSubstring(String S, String[] L) {  
     List<Integer> result=new ArrayList<Integer>();  
     if(S.length()==0||L.length==0||L[0].length()==0)  
     {  
       return result;  
     }  
     int m=S.length();  
     int k=L.length;  
     int n=L[0].length();  
     HashMap<String,Integer> toFind=new HashMap<String,Integer>();  
     HashMap<String,Integer> found=new HashMap<String,Integer>();  
     for(String s:L)  
     {  
       if(toFind.containsKey(s))  
       {  
         toFind.put(s,toFind.get(s)+1);  
       }  
       else  
       {  
         toFind.put(s,1);  
       }  
     }  
     for(int i=0;i<=m-n*k;i++)  
     {  
       found.clear();  
       int j;  
       for(j=0;j<k;j++)  
       {  
         int start=i+j*n;  
         String sub=S.substring(start,start+n);  
         if(!toFind.containsKey(sub))  
         {  
           break;  
         }  
         if(found.containsKey(sub))  
         {  
           found.put(sub,found.get(sub)+1);  
         }  
         else  
         {  
           found.put(sub,1);  
         }  
         if(found.get(sub)>toFind.get(sub))  
         {  
           break;  
         }  
       }  
       if(j==k)  
       {  
         result.add(i);  
       }  
     }  
     return result;  
   }  
 }  

No comments:

Post a Comment