beats 99.80% C++ solution


  • 0
    Y
    class ValidWordAbbr {
    public:
        ValidWordAbbr(vector<string> &dictionary): dict(dictionary) {
            for (int i = 0; i != dict.size(); ++i) {
                string abbr = str2abbr(dict[i]);
                auto iter = abbrs.find(abbr);
                if (iter == abbrs.end()) {
                    abbrs[abbr] = i;
                } else if (iter->second != -1 && dict[iter->second] != dict[i]) {
                    iter->second = -1;
                }
            }
        }
    
        bool isUnique(string word) {
            auto iter = abbrs.find(str2abbr(word));
            return iter == abbrs.end() || iter->second != -1 && dict[iter->second] == word;
        }
    private:
        static string str2abbr(const string & str) {
            int len = str.size();
            return len <= 2 ? str : (str.substr(0, 1) + to_string(len - 2) + str.substr(len - 1, 1));
        }
        
        vector<string> dict;
        unordered_map<string, int> abbrs;
    };
    

Log in to reply
 

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