LintCode 648: Unique Word Abbreviation

  1. 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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值