当有两个不同的 word 对应同一个 key 的时候,这个 key 就已经可以认为是 "作废" 了。
public class ValidWordAbbr {
HashMap<String, String> map;
public ValidWordAbbr(String[] dictionary) {
map = new HashMap<String, String>();
for (String word : dictionary) {
String key = getKey(word);
if (map.containsKey(key)) {
if (!map.get(key).equals(word)) { // If there is more than one string belong to the same key
// then the key will be invalid, we set the value to ""
map.put(key, "");
}
} else {
map.put(key, word);
}
}
}
public boolean isUnique(String word) {
return !map.containsKey(getKey(word)) || map.get(getKey(word)).equals(word);
}
private String getKey(String s) {
if (s.length() <= 2) return s;
String key = s.charAt(0) + Integer.toString(s.length() - 2) + s.charAt(s.length() - 1);
return key;
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");