29. Substring with Concatenation of All Words

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).

---

 

public class Solution {
    public ArrayList<Integer> findSubstring(String S, String[] L) {
         
        int len =  L[0].length();
        int count = L.length;
    
        HashMap<String, Integer> words = new HashMap<String, Integer> ();

        // put each words in L to the hashmap
        // key is the string, value is the count
        for ( String s:L ) {
            if ( words.containsKey( s ) ){
                words.put( s, 1+words.get(s) );
            } else {
                words.put( s, 1 );
            }
        }
        
        
        ArrayList<Integer> rst = new ArrayList<Integer>();
 
        int slen = S.length();
        // go through the S from left to right
        for ( int i=0; i<=slen-count*len; i++ ) {
            
            // use hash to store all the word we need to find
            HashMap<String, Integer> targets = new HashMap<String, Integer>  (words);
            int index = i;
            while ( true ) { 
                // catch a sub-word
                String sub = S.substring( index, index+len);
                
                // catch if it is one of the target
                if ( targets.containsKey ( sub ) ) {
                    if (targets.get(sub) == 1 ) targets.remove ( sub ) ;
                    else targets.put ( sub, targets.get (sub)-1 ) ;
                    
                    if ( targets.isEmpty() ) {// find a substring            
                        rst.add ( i );
                        break;
                    }
                    
                    // next sub-sowrd
                    index += len;
                } else {
                    // not our target,
                    break;
                }
            }     
        }
        return rst;
    }
}

 

posted @ 2013-09-23 07:55  LEDYC  阅读(261)  评论(0)    收藏  举报