Simple Concise C++ Solution.


  • 0
    Y
    class ValidWordAbbr {
    public:
        ValidWordAbbr(vector<string> &d) {
            for (const auto& w : d) {
                map[abbreviations(w)].push_back(w);
            }
        }
    
        bool isUnique(string word) {
            int cnt = map[abbreviations(word)].size();
            auto vec = map[abbreviations(word)];
            for(int i = 0; i < vec.size(); ++i) {
                if(vec[i] != word) {
                    return false;
                }
            }
            return true;
        }
    
    private:
        // Helper function to get the abbreviations
        string abbreviations(string s) {
            return s.size() <= 2 ? s : s[0] + to_string(s.size() - 2) + s.back();
        }
    
        unordered_map<string, vector<string>> map;
    };

  • 0

    Just a little alternative:
    return cnt == 0 || cnt == 1 && word == map[abbreviations(word)][0];


  • 0
    Y

    Thanks for the advice : )


  • 0
    Y

    how do you handle ["a","a"] isUnique("a") return true case?


  • 0
    Y

    I think leetcode updated the testcases, I've updated my solution, thanks.


  • 0
    Y

    Thank you for the updating. Then, vector might not be a good choice, since we have to iterate over the vector. We may have to use unordered_set as the second argument inside the map.
    I was looking a way to avoid the unordered_set, and curious how your solution could work. I did not know they updated the test case.


Log in to reply
 

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