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
1 public class ValidWordAbbr { 2 String[] dict; 3 HashMap<String, Set<String>> afterAbbr; 4 5 public ValidWordAbbr(String[] dictionary) { 6 this.dict = dictionary; 7 this.afterAbbr = new HashMap<String, Set<String>>(); 8 for (String item : dictionary) { 9 String str = abbr(item); 10 if (afterAbbr.containsKey(str)) { 11 afterAbbr.get(str).add(item); 12 } 13 else { 14 HashSet<String> set = new HashSet<String>(); 15 set.add(item); 16 afterAbbr.put(str, set); 17 } 18 } 19 } 20 21 public boolean isUnique(String word) { 22 String str = abbr(word); 23 if (!afterAbbr.containsKey(str)) return true; 24 else if (afterAbbr.containsKey(str) && afterAbbr.get(str).contains(word) && afterAbbr.get(str).size()==1) return true; 25 return false; 26 } 27 28 public String abbr(String item) { 29 if (item == null) return null; 30 if (item.length() <= 2) return item; 31 StringBuffer res = new StringBuffer(); 32 res.append(item.charAt(0)); 33 res.append(item.length()-2); 34 res.append(item.charAt(item.length()-1)); 35 return res.toString(); 36 } 37 } 38 39 40 // Your ValidWordAbbr object will be instantiated and called as such: 41 // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); 42 // vwa.isUnique("Word"); 43 // vwa.isUnique("anotherWord");
时间: 2024-10-15 04:18:36