Unique Word Abbreviation
An abbreviation of a word follows the form
a) it --> it (no abbreviation)
1
b) d|o|g --> d1g
1 1 1
1---5----0----5--8
c) i|nternationalizatio|n --> i18n
1
1---5----0
d) l|ocalizatio|n --> l10n
Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation.
Example:
Given dictionary = [ "deer", "door", "cake", "card" ]
isUnique("dear") -> false;
isUnique("cart") -> true
isUnique("cane") -> false
isUnique("make") -> true
Tips:
- 注意全局变量map,以及在哪里new map;
- 需要注意,字典里可能有重复选项,也可能这个词在字典里没有,所以
if (map.containsKey(abb)) {
if (!map.get(abb).equals(str)) {
map.put(abb,"");
}
}
还有一段:
return !map.containsKey(getAbb(word))||map.get(getAbb(word)).equals(word)
另外需要注意toString方法;
代码:
public class ValidWordAbbr {
HashMap<String, String> map;
public ValidWordAbbr(String[] dictionary) {
map = new HashMap<String, String>();
for (String str : dictionary) {
String abb = getAbb(str);
if (map.containsKey(abb)) {
if (!map.get(abb).equals(str)) {
map.put(abb,"");
}
} else {
map.put(abb, str);
}
}
}
public boolean isUnique(String word) {
return !map.containsKey(getAbb(word))||map.get(getAbb(word)).equals(word);
}
private String getAbb(String word) {
if (word.length() <= 2) {
return word;
}
String abb = word.charAt(0) + Integer.toString(word.length() - 2) + word.charAt(word.length() - 1);
return abb;
}
}
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");