C++ Solution Beats 98% Submissions


  • 0
    M
    class ValidWordAbbr {
        
    private:
        unordered_map<string, pair<int, string>> map;
    public:
        ValidWordAbbr(vector<string> dictionary) {
            for (int i = 0; i < dictionary.size(); i++) {
                string &word = dictionary[i];
                string s = to_abbr(word);
                if (s.empty()) {
                    continue;
                }
                
                if (map.find(s) != map.end()) {
                    map[s].first++;
                } else {
                    map[s] = make_pair(1, word);
                }
            }
        }
        
        bool isUnique(string word) {
            string s = to_abbr(word);
            if (s.empty()) {
                return true;
            }
            
            if (map.find(s) != map.end() && (map[s].first > 1 || word.compare(map[s].second) != 0)) {
                return false;
            }
            
            return true;
        }
        
        string to_abbr(string word) {
            int len = word.length();
            if (len <= 2) {
                return "";
            }
            return string(1, word[0]) + to_string(len - 2) + string(1, word[len - 1]);
        }
    };
    
    

Log in to reply
 

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