Unique Word Abbreviationspa
An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations:code
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.orm
Example: blog
Given dictionary = [ "deer", "door", "cake", "card" ] isUnique("dear") -> isUnique("cart") -> isUnique("cane") -> isUnique("make") -> falsetruefalsetrue
分析:字符串
其實題目沒有表達清楚...應該包含以下意思:string
1. dictionary = {"dear"}, isUnique("door") -> falsehash
2. dictionary = {"door", "door"}, isUnique("door") -> trueit
3. dictionary = {"dear", "door"}, isUnique("door") -> falseio
因此當縮寫存在時,也並不是必定要return false,若是原字典中與query縮寫一致的原字符串,如2中dict的兩個"door",與query原字符串"door"一致,那麼也應該return true。ast
代碼:
class Solution { private: string maptoabbr(string str) { string abbr = ""; abbr += str[0]; //若只有一位,則直接返回;有兩位,則中間不加數字;兩個以上,則加數字 if(str.length() > 1) { abbr += str.length() > 2 ? to_string(str.length() - 2) : ""; abbr += str.back(); } return abbr; } //hashabbr用來存儲縮寫後的字符串,hashorig用來存儲原始字符串 unordered_multiset<string> hashabbr, hashorig; public: Solution(vector<string> dict) { for(string str : dict) { hashorig.insert(str); hashabbr.insert(maptoabbr(str)); } } bool isUnique(string str) { string abbr = maptoabbr(str); //若是縮寫不存在字典中,直接return true if(hashabbr.find(abbr) == hashabbr.end()) return true; //若是縮寫在字典中,則若是query只對應一種原始字符串,則return true;不然return false return hashabbr.count(abbr) == hashorig.count(str); } };