[LeetCode288]Unique Word Abbreviation

来源:互联网 发布:npm 网络性能管理 编辑:程序博客网 时间:2024/05/19 14:35
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)     1b) d|o|g                   --> d1g              1    1  1     1---5----0----5--8c) i|nternationalizatio|n  --> i18n              1     1---5----0d) l|ocalizatio|n          --> l10nAssume 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") -> falseisUnique("cart") -> trueisUnique("cane") -> falseisUnique("make") -> trueHide Company Tags GoogleHide Tags Hash Table DesignHide 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");};
0 0