[leetcode]Substring with Concatenation of All Words

用hash暴力。。。

感觉是刚好过吧。。

开始里面多查了两次,就是TLE

class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
        int wordLen = L.front().size();
        int cut = L.size() * wordLen;
        int s_size = S.size();
        vector<int> ans;
        if(s_size < cut) return ans;
        unordered_map<string , int> dic;
        for(int i = 0 ; i < L.size() ; i++) dic[L[i]] ++;
        
        for(int i = 0 ; i <= s_size - cut ; i ++){
            //--
            unordered_map<string,int> tmp(dic);
            for(int j = i ; j < i + cut ; j += wordLen){
                string sub = S.substr(j , wordLen);
                auto found = tmp.find(sub);
                if(found == tmp.end() || found -> second == 0) break;
                found->second--;
                if(found -> second == 0) tmp.erase(found);
            }
            if(tmp.size() == 0) ans.push_back(i);
            
        }
        return ans;
    }
};
class Solution {
public:
    vector<int> findSubstring(string S, vector<string> &L) {
        unordered_map<string, int> cnt;
        int n = L.size();
        int len = L.front().size();
        for (auto& str : L) cnt[str]++;
        vector<int> ans;
        if (S.size() < n * len) return ans;

        for (int i = 0; i <= S.size() - n * len; i++) {
            unordered_map<string, int> tmp(cnt);
            for (int j = i; j < i + n * len; j += len) {
                string sub = S.substr(j, len);
                auto found = tmp.find(sub);
                if (found == tmp.end() || found->second == 0) break;
                found->second--;
                if (found->second == 0) {
                    tmp.erase(found);
                }
            }
            if (tmp.size() == 0) {
                ans.push_back(i);
            }
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/x1957/p/3511084.html