- Unique Word Abbreviation
中文English
An abbreviation of a word follows the form. 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
Example1
Input:
[ “deer”, “door”, “cake”, “card” ]
isUnique(“dear”)
isUnique(“cart”)
Output:
false
true
Explanation:
Dictionary’s abbreviation is [“d2r”, “d2r”, “c2e”, “c2d”].
“dear” 's abbreviation is “d2r” , in dictionary.
“cart” 's abbreviation is “c2t” , not in dictionary.
Example2
Input:
[ “deer”, “door”, “cake”, “card” ]
isUnique(“cane”)
isUnique(“make”)
Output:
false
true
Explanation:
Dictionary’s abbreviation is [“d2r”, “d2r”, “c2e”, “c2d”].
“cane” 's abbreviation is “c2e” , in dictionary.
“make” 's abbreviation is “m2e” , not in dictionary.
解法1:
用两个map,当word在原字典中的个数和缩写词在缩写字典中的个数相等时就返回true,否则false。
class ValidWordAbbr {
public:
/*
* @param dictionary: a list of words
*/
ValidWordAbbr(vector<string> dictionary) {
int n = dictionary.size();
for (int i = 0; i < n; ++i) {
string tmpStr = dictionary[i];
wordMap[tmpStr]++;
if (tmpStr.size() < 3)
abrMap[tmpStr]++;
else {
abrMap[tmpStr[0] + to_string(tmpStr.size() - 2) + tmpStr[tmpStr.size() - 1]]++;
}
}
}
/*
* @param word: a string
* @return: true if its abbreviation is unique or false
*/
bool isUnique(string &word) {
string updatedWord;
if (word.size() < 3)
updatedWord = word;
else
updatedWord = word[0] + to_string(word.size() - 2) + word[word.size() - 1];
if (abrMap.find(updatedWord) == abrMap.end()) return false;
if (abrMap[updatedWord] == wordMap[word]) return true;
return false;
}
private:
unordered_map<string, int> abrMap;
unordered_map<string, int> wordMap;
};
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr obj = new ValidWordAbbr(dictionary);
* bool param = obj.isUnique(word);
*/