[LeetCode288]Unique Word Abbreviation

An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations:

a) it                      --> it    (no abbreviation)

     1
b) d|o|g                   --> d1g

              1    1  1
     1---5----0----5--8
c) i|nternationalizatio|n  --> i18n

              1
     1---5----0
d) l|ocalizatio|n          --> l10n
Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation.

Example: 
Given dictionary = [ "deer", "door", "cake", "card" ]

isUnique("dear") -> false
isUnique("cart") -> true
isUnique("cane") -> false
isUnique("make") -> true
Hide Company Tags Google
Hide Tags Hash Table Design
Hide Similar Problems (E) Two Sum III - Data structure design

剛開始覺得就是找出abbreviation當key 把自己加到hashtable裏,然後看每個key的size是不是1就可以判斷是不是unique word了,但是發現了這句話A word's abbreviation is unique if no other word from the dictionary has the same abbreviation. 就比如a,a,a自己的縮寫和自己一樣,也算unique的。

有兩種structure可以用,vector 和set。

class ValidWordAbbr {
public:
    ValidWordAbbr(vector<string> &dictionary) {
        for(string s : dictionary){
            mp[abbrivate(s)].push_back(s);
        }
    }
    string abbrivate(string s){
        int len = s.size();
        return len<=2 ? s : s[0] + to_string(len-2) + s[len-1];
    }
    bool isUnique(string word) {
        for(string s : mp[abbrivate(word)]){
            if(s != word) return false;
        }
        return true;
    }
private: unordered_map<string, vector<string>> mp;
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa(dictionary);
// vwa.isUnique("hello");
// vwa.isUnique("anotherWord");
};
class ValidWordAbbr {
public:
    ValidWordAbbr(vector<string> &dictionary) {
        for(string s : dictionary){
            mp[abbrivate(s)].push_back(s);
        }
    }
    string abbrivate(string s){
        int len = s.size();
        return len<=2 ? s : s[0] + to_string(len-2) + s[len-1];
    }
    bool isUnique(string word) {
        return (mp[abbrivate(word)].size() == 1 && mp[abbrivate(word)].find(word) != mp[abbrivate(word)].end()) || mp[abbrivate(word)].empty();
    }
private: unordered_map<string, unordered_set<string>> mp;
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa(dictionary);
// vwa.isUnique("hello");
// vwa.isUnique("anotherWord");
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章