Open yokostan opened 5 years ago
class ValidWordAbbr { HashMap<String, String> map = new HashMap<>(); public ValidWordAbbr(String[] dictionary) { for (String str : dictionary) { String key = getKey(str); if (map.containsKey(key)) { if (!map.get(key).equals(str)) { map.put(key, ""); } } else { map.put(key, str); } } } public boolean isUnique(String word) { return !map.containsKey(getKey(word)) || map.get(getKey(word)).equals(word); } public String getKey(String str) { if (str.length() <= 2) return str; return str.charAt(0) + Integer.toString(str.length() - 2) + str.charAt(str.length() - 1); } } /** * Your ValidWordAbbr object will be instantiated and called as such: * ValidWordAbbr obj = new ValidWordAbbr(dictionary); * boolean param_1 = obj.isUnique(word); */