How can I improve my solution?


  • 0
    R

    Hi, this is my code, just a very simple method of using two map, ..., but it is timelimit and I wonder if I can add some optimization to pass the limit with the same method?

    class Solution {
    public:
        vector<int> findSubstring(string s, vector<string>& words) {
            int wordsLen=words.size();
        	if(s.size()==0 || wordsLen==0) return vector<int>();
            unordered_map<string, int> word_to_count;
            for(int i=0; i<wordsLen; ++i)
                word_to_count[words[i]]++;
            int len=words[0].size(), sum=0;
            vector<int> result;
    	    int sSize=s.size();
    	    unordered_map<string, int> Map;
            
            for(int i=0; i<=sSize-len; ++i) {
                Map.clear();
                sum=0;
                for(int j=i; j<=sSize-len; j+=len) {
    		        string word=s.substr(j, len);
                    if(word_to_count.count(word)){
                        Map[word]++;
                        if(Map[word]>word_to_count[word]) break;
                        else sum++;
                    }
                    else break;
                }
                if(sum==wordsLen) result.push_back(i);
            }
            return result;    
        }
    };

  • 0
    C

    if(word_to_count.find(word)==word_to_count.end()) break;


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.