zoukankan      html  css  js  c++  java
  • Unique Word Abbreviation -- LeetCode

    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)判断要检测的单词是否在所给的字典中。

  • 相关阅读:
    EJB 3.0持久化规范之实体类的要求
    Java正则表达式应用总结
    Java正则表达式教程
    JS正则表达式大全
    Sql Server 配置 及 Hibernate 驱动配置
    EJB QL查询语言
    解决多个jquery文件,造成jquery文件冲突的方法
    ps之网页设计企业站建设推荐
    zencart程序文件目录
    Database server does not support the InnoDB storage engine MAGENTO 安装提示错误
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5767729.html
Copyright © 2011-2022 走看看