LeetCode|Substring with Concatenation of All Words(すべての単語をリンクするサブストリング)

1801 ワード

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).
テーマ解析:
この问题は长い间悩んでいました......c++に详しくないので、ずっとcで実现したいと思っていましたが、结果はとても面倒で、どの大神がcで成功して実现して、分かち合うことを忘れました......
c++のmapを使うのはかなり簡単で、まずLの中の文字列をmapの中でマッピングを確立します.そして、Sは、往き後からいずれかを先頭文字として長さl_を判定するsize*word_sizeの連続文字列がmapにあるかどうか.もちろんLに重複する文字列が出ないようにcountingを別途設けてサブストリングの個数を記録し,個数がword_を超えるとcount[word]の場合も、終了して、Sの次の文字を巡ります.
class Solution {
public:
    vector findSubstring(string S, vector &L) {
        int l_size = L.size();
        vector res;
        if(l_size <= 0)
            return res;

        map word_count; //  L              
        int word_size = L[0].size();
        for(int i = 0;i < l_size;i++)
            ++word_count[L[i]];
        map counting;   //          
        for(int i = 0;i <= (int)S.size()-l_size*word_size;i++){
            counting.clear();
            int j;
            for(j = 0;j < l_size;j++){
                string word = S.substr(i+j*word_size,word_size);
                if(word_count.find(word) != word_count.end()){
                    ++counting[word];
                    if(counting[word] > word_count[word])
                        break;
                }else
                    break;
            }
            if(j == l_size)
                res.push_back(i);
        }
        return res;
    }
};