30. Substring with Concatenation of All Words

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

For example, given:
s:"barfoothefoobarman"
words:["foo", "bar"]

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

思路:不会

public class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> list = new ArrayList<Integer>();
        if (s==null||words==null||words.length==0)
            return list;

        Map<String, Integer> map = new HashMap<String, Integer>();


        int len = words[0].length();

        for (String word:words){
            map.put(word,map.containsKey(word)?map.get(word)+1:1);
        }

        for (int i=0;i<=s.length()-len*words.length;i++){
            Map<String, Integer> copy = new HashMap<String,Integer>(map);
            for (int j=0;j<words.length;j++){
                String Subs = s.substring(i+j*len,i+(j+1)*len);
                if (copy.containsKey(Subs)){
                    int count = copy.get(Subs);
                    if (count==1){
                        copy.remove(Subs);
                    }else{
                        copy.put(Subs,count-1);
                    }
                    if (copy.isEmpty()){
                        list.add(i);
                        break;
                    }
                }else
                {
                    break;
                }
            }
        }

        return list;
    }
};

results matching ""

    No results matching ""