Clean code with hashtable


  • 0
    W

    use counter indicate whether a substring of s is matched, when counter == 0 there is a match

    class Solution {
    public:
        vector<int> findSubstring(string s, vector<string>& words) {
            unordered_map<string, int> m;
            for (auto s:words) m[s]++;
            const int len = words[0].size();
            int counter = words.size();
            vector<int> res;
            
            for (int i = 0; i+len*words.size()-1 < s.size(); i++) {
                int start = i;
                while (m[s.substr(start,len)]-- > 0) {counter--; start += len;}
                if (counter == 0) res.push_back(i);
                if (counter != words.size()) {
                    counter = words.size();
                    m.clear();
                    for (auto s:words) m[s]++;
                }
            }
            return res;
        }
    };

Log in to reply
 

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