Got runtime error for Substring with Concatenation of All Words, code works fine in local


  • 0
    M
    vector<int> findSubstring(string s, vector<string>& words) {
    
        int wordLen = words[0].size();
        map<string, int> expectedCount;
        map<string, int> actualCount;
        for (int i=0; i<words.size(); i++) {
    
            expectedCount[words[i]] = expectedCount[words[i]]++;
    
    
        }
    
        vector<int> res;
    
        for (int i=0; i<wordLen; i++) {
            int left = i;
            int count = 0;
            for (int j=i; j<=(int)s.length()-wordLen;j=j+wordLen) {
                string str=s.substr(j, wordLen);
                if (expectedCount.find(str)!=expectedCount.end()) {
                    actualCount[str]++;
    
                    if (actualCount[str]<=expectedCount[str]) {
                        count++;
                    } else {
                        while (actualCount[str]>expectedCount[str]) {
                            string temp = s.substr(left, wordLen);
                            actualCount[temp]=actualCount[temp]--;
                            if (actualCount[temp]<expectedCount[temp])
                                count--;
                            left=left+wordLen;
                        }
                    }
    
                    if (count==words.size()) {
                        res.push_back(left);
                        string temp = s.substr(left, wordLen);
                            actualCount[temp]=actualCount[temp]--;
                        if (actualCount[temp]<expectedCount[temp])
                        count--;
                        left=left+wordLen;
                    }
    
                } else {
                    count=0;
                    actualCount.clear();
                    left=j+wordLen;
                }
            }
        }
    
        return res;
    }

Log in to reply
 

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