C++ object oriented solution


  • 0
    S
    class ValidWordAbbr {
    public:
    
        ValidWordAbbr(vector<string> &dictionary) {
            for (string w : dictionary){
                bag.insert(w);
            }
        }
    
        bool isUnique(string word) {
            return bag.isUnique(word);
        }
    
    private:
        struct Bag{
            unordered_map<string,int> abr_dict;
            unordered_set<string> bag_words;
            
            string abr(string word){
                int n = word.size();
                if (n < 3) return word;
                string res = word[0] + to_string(n - 2) + word[n - 1];
                return res;
            }
            void insert(string word){
                auto ret = bag_words.insert(word);
                if (ret.second){
                    string w_abr = abr(word);
                    abr_dict.find(w_abr) == abr_dict.end() ? abr_dict[w_abr] = 1 : ++abr_dict[w_abr];
                }
            }
            bool isUnique(string word){
                if (abr_dict.find(abr(word)) == abr_dict.end()) {
                    return true;
                } else if (abr_dict[abr(word)] == 1 && bag_words.find(word) != bag_words.end()) {
                    return true;
                }
                return false;
            }
        };
        
        Bag bag;
    };
    

Log in to reply
 

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