1 public class ValidWordAbbr { 2 private Map> dict; 3 public ValidWordAbbr(String[] dictionary) { 4 dict = new HashMap<>(); 5 for (String word : dictionary) { 6 String str = processStr(word); 7 if (!dict.containsKey(str)) { 8 dict.put(str, new HashSet<>()); 9 }10 dict.get(str).add(word);11 }12 }13 14 public boolean isUnique(String word) {15 String str = processStr(word);16 if (!dict.containsKey(str) || dict.get(str).contains(word) && dict.get(str).size() == 1) {17 return true;18 }19 return false;20 }21 22 private String processStr(String word) {23 if (word.length() <= 2) {24 return word;25 }26 StringBuilder result = new StringBuilder();27 result.append(word.charAt(0));28 result.append(word.length() - 2);29 result.append(word.charAt(word.length() - 1));30 return result.toString();31 32 }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");
Remember: need to check whether has the word in hashset and garantee size is one.