An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations:
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
一刷
题解:用map abbreviation->word来求解,很简单
但是要注意,如果dict里面有word, 有唯一unique, 那么isUnique(word)应该返回true.
所以用一个set来保存所有的dict里面的abbreviation是行不通的。必须保存原先的word。那么如果dict中有两个不同word有同一个abbreviation呢
于是该用Map<String,Set<String>> map;
class ValidWordAbbr {
private Map<String,Set<String>> abbr;
public ValidWordAbbr(String[] dictionary) {
abbr = new HashMap<>();
for(String str:dictionary){
String a = getAbb(str);
if(abbr.containsKey(a)){
Set<String> s = abbr.get(a);
if(!s.contains(str)) s.add(str);
}else{
Set<String> s = new HashSet();
s.add(str);
abbr.put(a,s);
}
}
}
public boolean isUnique(String word) {
String abb = getAbb(word);
Set<String> s = abbr.get(abb);
if(s == null) return true;
if(s.size()>1) return false;
if(s.contains(word)) return true;
return false;
}
public String getAbb(String str){
if(str.length() <= 2){
return str;
}
StringBuilder sb = new StringBuilder(3);
sb.append(str.charAt(0));
sb.append(str.length()-2);
sb.append(str.charAt(str.length()-1));
return sb.toString();
}
}
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr obj = new ValidWordAbbr(dictionary);
* boolean param_1 = obj.isUnique(word);
*/
方法二,
用Map<String, String> map; 如果在dict中,不同的word有同一个abbreviation, 那么直接把map的value置为“”
class ValidWordAbbr {
/*
If there is more than one string belong to the same key
then the key will be invalid, we set the value to ""
*/
Map<String, String> map;
public ValidWordAbbr(String[] dictionary) {
map = new HashMap<String, String>();
for (String word : dictionary) {
String key = toAbbr(word);
if (!map.containsKey(key))
map.put(key, word);
else if (!map.get(key).equals(word))
map.put(key, "");
}
}
public boolean isUnique(String word) {
String key = toAbbr(word);
return !map.containsKey(key) || map.get(key).equals(word);
}
private String toAbbr(String str) {
if (str.length() <= 2)
return str;
else
return str.charAt(0) + String.valueOf(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);
*/