• + 0 comments

    This is my solution, which rispects the time limit too, and w/o a tree structure.

    template<const unsigned char SIZE = 26, 
             const char START = 'a'> 
    struct HashMapName{
        std::vector<const std::string*> bucket[SIZE];
        void add(const std::string* name)
        {
            char hash = (*name)[0] - START;
            if(hash < 0 || hash >= SIZE) return;
            bucket[size_t(hash)].emplace_back(name);
        }
        void find(const std::string& fname, int& count) 
        {
            char hash = fname[0] - START;
            if(hash < 0 || hash >= SIZE) return;
            
            for(const auto* const name : bucket[size_t(hash)]) {
                if (name->size() < fname.size()) 
                    continue;
                else if (strncmp(name->c_str(), 
                                    fname.c_str(), 
                                    fname.size()) == 0) 
                    count += 1;
            }
        }
    };
    
    
    vector<int> contacts(const vector<vector<string>>&  queries) {
        vector<int> count_finds;
        HashMapName<26,'a'> contacts_names;
        count_finds.reserve(queries.size() / 2);
        for(const auto& qsplit : queries) 
        {
            if(qsplit[0][0] == 'a') {
                contacts_names.add(&qsplit[1]);
            }
            else if(qsplit[0][0] == 'f') {
                count_finds.push_back(0);
                auto& count = count_finds.back();
                const auto& fname = qsplit[1];
                contacts_names.find(fname, count);
            }
        }
        return std::move(count_finds);
    }