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

Code1 : Two Maps (one for record, the other for scanning)

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> indices;
        if (s.size() == 0 or words.size() == 0) return indices; 
        unordered_map<string, int> counts;
        for (string word : words)
            counts[word]++;

        int n = s.size(), num = words.size(), len = words[0].length();
        for (int i = 0; i <= n - num * len; i++) {
            unordered_map<string, int> seen;
            int j = 0;
            for (; j < num; j++) {
                string word = s.substr(i + j * len, len);
                if (counts.find(word) != counts.end()) {
                    seen[word]++;
                    if (seen[word] > counts[word]) // overuse
                        break;
                } 
                else break; // did not find
            }
            if (j == num) indices.push_back(i);
        }
        return indices;
    }
};

Code2 (Java) by harrychaoyanghe

My C++ Implementation based on Code 2:

Last updated

Was this helpful?