当有两个不同的 word 对应同一个 key 的时候,这个 key 就已经可以认为是 "作废" 了。
publicclassValidWordAbbr {HashMap<String,String> map;publicValidWordAbbr(String[] dictionary) { map =newHashMap<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); } } }publicbooleanisUnique(String word) {return!map.containsKey(getKey(word)) ||map.get(getKey(word)).equals(word); }privateStringgetKey(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");