2014年12月3日星期三

[Leetcode] 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).

Brute Force, enumerate each substring and check the word in the substring to see if it satisfy the constriction. I first build a hashmap on the L to record the count for each word, and while checking the substring, we also build such a hashmap, whenever we find a word that is not in the L, we terminate the checking and go to next one, or we find a word that appears more than those in L. Otherwise we have find a valid substring and we add the index to the result set.


    public List<Integer> findSubstring(String S, String[] L) {
        List<Integer> res = new ArrayList<Integer>();
        int n = L.length;
        if(n == 0)
            return res;
        int m = L[0].length();
        int len = S.length();
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for(int i = 0; i < n; i++) {
            if(map.containsKey(L[i]) == false)
                map.put(L[i], 1);
            else
                map.put(L[i], map.get(L[i]) + 1);
        }
        HashMap<String, Integer> count = new HashMap<String, Integer>();
        for(int i = 0; i <= len - n*m; i++) {
            count.clear();
            int j = i;
            for(j = i; j < i + n*m; j += m) {
                String str = S.substring(j, j+m);
                if(map.containsKey(str) == false)
                    break;
                else {
                    if(count.containsKey(str) == false)
                        count.put(str, 1);
                    else {
                        if(count.get(str) >= map.get(str))
                            break;
                        else
                            count.put(str, count.get(str) + 1);
                    }
                }
            }
            if(j == i + n*m)
                res.add(i);
        }
        return res;
    }

没有评论:

发表评论