Why my code "Time Limit Exceeded"


  • 0
    class Solution
    {
    public:
        vector<int> findSubstring(string S, vector<string> &L)
        {
            vector<int> vi;
            if(L.size() == 0)
                return vi;
    
            unordered_multiset<string> ss(L.cbegin(), L.cend());
            for(int i = 0; i < L[0].size(); ++ i)
            {
                unordered_multiset<string> stemp;
                int b = i;
                for(int j = b; j + L[0].size() <= S.size(); j += L[0].size())
                {
                    string str = S.substr(j, L[0].size());
                    if(ss.find(str) != ss.end())
                    {
                        if(stemp.count(str) < ss.count(str))
                        {
                            stemp.insert(str);
                            if(stemp.size() == ss.size())
                            {
                                vi.push_back(b);
                                stemp.erase(stemp.find(S.substr(b, L[0].size())));
                                b += L[0].size();
                            }
                        }
                        else
                        {
                            for(string s; (s = S.substr(b, L[0].size())) != str; stemp.erase(stemp.find(s)))
                                b += L[0].size();
                            b += L[0].size();
                        }
                    }
                    else
                    {
                        stemp.clear();
                        b = j + L[0].size();
                    }
                }
            }
            return vi;
        }
    };

Log in to reply
 

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