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) in s that is a concatenation of each word in words exactly 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).

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> result;
        int m = s.length();
        int n = words.size();
        int k = words[0].length();

        map<string, int> buf;
        for (int i = 0; i < n; i++)
        {
            if (buf.find(words[i]) == buf.end())
            {
                buf[words[i]] = 1;
            }
            else
            {
                buf[words[i]]++;
            }
        }

        for (int i = 0; i <= m-n*k; i++)
        {
            map<string, int> temp(buf);
            bool found = true;
            for (int j = i; j < i+n*k; j += k)
            {
                string str = s.substr(j, k);
                if (temp.find(str) == temp.end())
                {
                    found = false;
                    break;
                }
                else
                {
                    temp[str]--;
                    if (temp[str] < 0)
                    {
                        found = false;
                        break;
                    }
                }
            }

            if (found)
            {
                result.push_back(i);
            }
        }

        return result;
    }
};


你可能感兴趣的:(Substring with Concatenation of All Words)