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
Show Company Tags
Show Tags
Show Similar Problems
1 class ValidWordAbbr { 2 private: 3 unordered_map<string, int> dict; 4 unordered_set<string> inDict; 5 string getAbbr(string word) { 6 if (word.size() < 3) return word; 7 return word.front() + std::to_string(word.size() - 2) + word.back(); 8 } 9 public: 10 ValidWordAbbr(vector<string> &dictionary) { 11 for (int i = 0, n = dictionary.size(); i < n; i++) { 12 if (inDict.count(dictionary[i])) continue; 13 inDict.insert(dictionary[i]); 14 string abbr = getAbbr(dictionary[i]); 15 if (dict.count(abbr) == 0) 16 dict.insert(make_pair(abbr, 1)); 17 else dict[abbr]++; 18 } 19 } 20 21 bool isUnique(string word) { 22 string abbr = getAbbr(word); 23 if (dict.count(abbr) == 0 || (dict[abbr] == 1 && inDict.count(word) == 1)) 24 return true; 25 return false; 26 } 27 }; 28 29 30 // Your ValidWordAbbr object will be instantiated and called as such: 31 // ValidWordAbbr vwa(dictionary); 32 // vwa.isUnique("hello"); 33 // vwa.isUnique("anotherWord");
要点:int转string可以用函数std::to_string()
inDict 的作用有两个:1)将所给的字典去重。 2)判断要检测的单词是否在所给的字典中。
时间: 2024-10-14 00:38:56