*leetcode 30 findSubstring

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

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {

        vector<int> ret;
        multiset<string> sset;
        typedef multiset<string>::iterator iter;

        size_t size = words[0].size();  
        size_t vSize = words.size(); 
        size_t sSize = s.size();

        if (vSize * size > sSize) return vector<int>();

        for (size_t i = 0; i < vSize; ++i) { 
            sset.insert(words[i]);
        }

        size_t i = 0;

        while (i < sSize) {
            multiset<string> setTmp(sset);

            size_t j = i;

            while (j < i + size * vSize) {
                string sTmp(s.substr(j, size));

                iter it = setTmp.find(sTmp);
                if (it != setTmp.end()) {
                    setTmp.erase(it);
                    j += size;
                }    
                else break;  
            }

            if (setTmp.empty()) ret.push_back(i);
            ++i;
        }

        return ret;
    }
};

参考后
sliding window

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        int wordlen = words[0].size();
        int strlen = s.size();
        int vsize = words.size();
        vector<int> ret;
        unordered_map<string, int> m;

        for (int i = 0; i < vsize; ++i) m[words[i]]++;

        for (int i = 0; i < wordlen; ++i) {
            unordered_map<string, int> tm;
            int count = 0;
            int left = i;

            for (int j = i; j <= strlen - wordlen; j += wordlen) {
                string tstr = s.substr(j, wordlen);

                if(m.count(tstr)) {
                    tm[tstr]++;
                    count++;

                     //出现重复子字符串        
                    while (tm[tstr] > m[tstr]) {
                        string str1(s.substr(left, wordlen));
                        --tm[str1];
                        left += wordlen;
                        --count;
                    }  

                    // 上一步处理后count < vsize; 未处理 count <= vsize;                
                    if (count == vsize) {
                            ret.push_back(left);
                            string str1(s.substr(left, wordlen));
                            --tm[str1];
                            left += wordlen;
                            --count;
                    }                
                } else {
                    left = j + wordlen;
                    count = 0;
                    tm.clear();
                }
            }
        }

        return ret;

    }
};

你可能感兴趣的:(leetcode,笔记,leetcode)