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) b) d|o|g --> d1g 1 1 1---5----0----5--8 c) i|nternationalizatio|n --> i18n 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
要注意一种情况:isUnique("cake"), 应该是true. 虽然他的缩写在afterabbr出现,但是那就是他自己,没有别的跟他一样
public class ValidWordAbbr { String[] dict; HashMap<String, Set<String>> afterAbbr; public ValidWordAbbr(String[] dictionary) { this.dict = dictionary; this.afterAbbr = new HashMap<String, Set<String>>(); for (String item : dictionary) { String str = abbr(item); if (afterAbbr.containsKey(str)) { afterAbbr.get(str).add(item); } else { HashSet<String> set = new HashSet<String>(); set.add(item); afterAbbr.put(str, set); } } } public boolean isUnique(String word) { String str = abbr(word); if (!afterAbbr.containsKey(str)) return true; else if (afterAbbr.containsKey(str) && afterAbbr.get(str).contains(word) && afterAbbr.get(str).size()==1) return true; return false; } public String abbr(String item) { if (item == null) return null; if (item.length() <= 2) return item; StringBuffer res = new StringBuffer(); res.append(item.charAt(0)); res.append(item.length()-2); res.append(item.charAt(item.length()-1)); return res.toString(); } } // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); // vwa.isUnique("Word"); // vwa.isUnique("anotherWord");