1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Substring with Concatenation of All Words

Posted on 2014-01-08 17:30  1957  阅读(162)  评论(0编辑  收藏  举报

用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;
    }
};