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

    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
    
    Solution:
     1 public class ValidWordAbbr {
     2     Map<String, String> abbrMap;
     3 
     4     public ValidWordAbbr(String[] dictionary) {
     5         abbrMap = new HashMap<String, String>();
     6 
     7         for (String word : dictionary) {
     8             String abbr = getAbbr(word);
     9             // the abbr is invalid, if it exsits and the corresponding word is not current word.
    10             if (abbrMap.containsKey(abbr) && !abbrMap.get(abbr).equals(word)) {
    11                 abbrMap.put(abbr, "");
    12             } else {
    13                 abbrMap.put(abbr, word);
    14             }
    15         }
    16     }
    17 
    18     public boolean isUnique(String word) {
    19         String abbr = getAbbr(word);
    20         // true, if @abbr does not exsit or the corresponding word is the @word.
    21         return (!abbrMap.containsKey(abbr)) || (abbrMap.containsKey(abbr) && abbrMap.get(abbr).equals(word));
    22     }
    23 
    24     public String getAbbr(String word){
    25     if (word.length()<=2) return word;
    26 
    27     StringBuilder builder = new StringBuilder();
    28     builder.append(word.charAt(0));
    29     builder.append(word.length()-2);
    30     builder.append(word.charAt(word.length()-1));
    31 
    32     return builder.toString();
    33     }
    34 }
    35 
    36 // Your ValidWordAbbr object will be instantiated and called as such:
    37 // ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
    38 // vwa.isUnique("Word");
    39 // vwa.isUnique("anotherWord");
  • 相关阅读:
    Pausing Coyote HTTP/1.1 on http-8080
    网站后台管理中生成首页失败
    Eclipse快捷键集结
    电子商务网站推广10大方法
    Eclipse使用
    注册表中更换桌面背景
    网站卡死,照惯例运行.bat批量处理文件进行重启不起作用
    同时处理html+js+jquery+css的插件安装(Spket&Aptana插件安装)
    JQuery的插件
    Eclipse插件
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5820462.html
Copyright © 2011-2022 走看看