Leetcode——Substring with Concatenation of All Word

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 wordsexactly once and without any intervening characters.spa

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

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


問題描述如上string

解題:it

先使用一個map(C++ 11中可使用unordered_map)來保存每一個單詞在words中出現的次數,注意一個單詞可能會出現屢次。因爲每一個單詞的長度相同,因此掃描窗口的長度爲word_size * words.size()。
io

首先將窗口置於s的起始位置,將窗口截成一個個word長度的串,掃描這些串是否在前面保存的map中存在,而且出現的次數相同。若是存在且相同,那麼表示找到了一個match。class

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        map<string, int> record;
        map<string, int> count;
        vector<int> pos;
        if (words.size() == 0)
        {
            return pos;
        }
        int word_size = (words[0]).size();
        if (s.size() < word_size*words.size())
        {
            return pos;
        }
        
        for (int i=0; i<words.size(); i++)
        {
            if (record.find(words[i]) == record.end())
            {
                record[words[i]] = 1;
            }else{
                record[words[i]]++;
            }
        }
        
        int i, j;
        for (i=0; i< s.size()-word_size*words.size()+1 ; i++)
        {
            count.clear();
            for (j=0; j<words.size(); j++)
            {
                string current_word = s.substr(i+j*word_size, word_size);
                if (record.find(current_word) != record.end())
                {
                    if (count.find(current_word) == count.end())
                    {
                        count[current_word] = 1;
                    }else{
                        count[current_word]++;
                    }
                    if (count[current_word] > record[current_word])
                    {
                        break;
                    }
                }else{
                    break;
                }
            }
            if (j == words.size())
            {
                pos.push_back(i);
            }
        }
        
        return pos;
    }
};
相關文章
相關標籤/搜索