首页 > 代码库 > 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") ->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");
LeetCode-Unique Word Abbreviation
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。