Beat 99.55% C++ solution


  • 0
    J
    class ValidWordAbbr {
        unordered_map<string, vector<string>> mp;//assume no repeated word in dictionary
    public:
        ValidWordAbbr(vector<string> dictionary) {
            for(auto word:dictionary)
            {
                int len=word.length();
                string abbr=GetAbbr(word);
                
                mp[abbr].push_back(word);
            }
        }
        
        bool isUnique(string word) {
            string abbr=GetAbbr(word);
            if(mp.find(abbr)!=mp.end())
            {
                vector<string> words=mp[abbr];
                for(auto w:words)
                {
                    if(w!=word)
                        return false;
                }
            }
            return true;
            
        }
        
        string GetAbbr(string word)
        {
            string abbr;
            int sz=word.length();
            if(sz<=2)
               abbr=word;
            else
            {
               abbr.push_back(word[0]);
               abbr.push_back(sz-2+'0');
               abbr.push_back(word[sz-1]);
                 
            }
            return abbr;
        }
    };
    

Log in to reply
 

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