LetCode 30. 与所有单词相关联的字串

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();

class Solution {
public:
    vector findSubstring(string s, vector& words) {
        vector res;
        if (s.length() <= 0 || words.size() <= 0)
            return res;
        unordered_map list;
        unordered_map temp;
        for (string word : words)
            list[word]++;
        int word_len = words[0].length();
        int word_num = words.size();
        int words_len = word_num * word_len;
        int len = s.length();
        int i, j;
        for (i = 0; i < word_len; i++) {
            int left = i;
            int cnt = 0;
            for (j = i; j <= len - word_len; j += word_len) {
                string str = s.substr(j, word_len);
                if (list.count(str) == 1) {
                    temp[str]++;
                    if (temp[str] <= list[str])
                        cnt++;
                    else {
                        // 清除前面的单词
                        while (temp[str] > list[str]) {
                            string t = s.substr(left, word_len);
                            temp[t]--;
                            if (temp[t] < list[t]) 
                                cnt--;
                            left += word_len;
                        }
                    }
                    // 滑动窗口
                    if (cnt == word_num) {
                        res.push_back(left);
                        temp[s.substr(left, word_len)]--;
                        cnt--;
                        left += word_len;
                    }
                }
                else {
                    temp.clear();
                    cnt = 0;
                    left = j + word_len;
                }
            }
            temp.clear();
        }
        return res;
    }
};

你可能感兴趣的:(LetCode)