LintCode 648: Unique Word Abbreviation
- 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 11---5----0----5--8
c) i|nternationalizatio|n --> i18n
11---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 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 abrMap;unordered_map wordMap;};/*** Your ValidWordAbbr object will be instantiated and called as such:* ValidWordAbbr obj = new ValidWordAbbr(dictionary);* bool param = obj.isUnique(word);*/
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
