Unique Word Abbreviation
Last updated
Last updated
class ValidWordAbbr {
private String abbrev(String word) {
StringBuilder sb = new StringBuilder();
if (word.length() > 2) {
sb.append(word.charAt(0)).append(word.length() - 2).append(word.charAt(word.length() - 1));
} else {
sb.append(word);
}
return sb.toString();
}
Map<String, String> map = new HashMap<>();
public ValidWordAbbr(String[] dictionary) {
for (String str : dictionary) {
String abbr = abbrev(str);
if (!map.containsKey(abbr)) {
map.put(abbr, str);
} else if (!map.get(abbr).equals(str)) {
map.put(abbr, "");
}
}
}
public boolean isUnique(String word) {
String abbr = abbrev(word);
return !map.containsKey(abbr) || map.get(abbr).equals(word);
}
}
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr obj = new ValidWordAbbr(dictionary);
* boolean param_1 = obj.isUnique(word);
*/