首页 > 代码库 > LeetCode-Unique Word Abbreviation

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)     1b) d|o|g                   --> d1g              1    1  1     1---5----0----5--8c) i|nternationalizatio|n  --> i18n              1     1---5----0d) 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") -> falseisUnique("cart") -> trueisUnique("cane") -> falseisUnique("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");

 

LeetCode-Unique Word Abbreviation