• 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");
  • 相关阅读:
    SQL Server CHARINDEX和PATINDEX详解
    Delphi7控件包详解 (转)
    经历一次人际关系危机总结,改进
    2008年5月份目标和计划
    God bless 贝贝!
    开始新的生活~~~
    一切安好~~~
    Hadoop : “Moving Computation is Cheaper than Moving Data”
    改论文,不轻言放弃,力求准确,简洁
    杜绝拖拖拉拉《明日歌》
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5820462.html
Copyright © 2020-2023  润新知