LeetCode 30 - Substring with Concatenation of All Words

来源:互联网 发布:c语言产生0 9的随机数 编辑:程序博客网 时间:2024/05/01 17:37

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

My Code

class Solution {public:    vector<int> findSubstring(string s, vector<string>& words) {        int words_size = words.size();        int word_len = words[0].length();        int s_len = s.length();        unordered_map<string, int> words_cnt;        for (int i = 0; i < words_size; i++)            words_cnt[words[i]]++;        vector<int> indices;        for (int i = 0; i <= s_len - words_size * word_len; i++)        {            unordered_map<string, int> occurences;            bool flag = true;            for (int j = 0; j < words_size; j++)            {                string word = s.substr(i + j * word_len, word_len);                if (words_cnt.find(word) != words_cnt.end())                    occurences[word]++;                else                {                    flag = false;                    break;                }                if (occurences[word] > words_cnt[word])                {                    flag = false;                    break;                }            }            if (flag)                indices.push_back(i);        }        return indices;    }};
Runtime: 776 ms

Notice

There may be duplicate word in words. So we need one more unordered_map to record count of each word.

0 0