An abbreviation of a word follows the form . 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---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 nootherword from the dictionary has the same abbreviation.
Example:
Given dictionary = [ "deer", "door", "cake", "card" ]isUnique("dear") ->falseisUnique("cart") ->trueisUnique("cane") ->falseisUnique("make") ->true
这题太恶心了, 一刷就各种整不明白, 写了一堆堆恶心代码, 最后还不对, 今天看攻略发现不但要逻辑正确, 还对代码的简洁度有要求。 尼玛, 这条路太难走了, 全是坎儿啊,竟是坑。
看了大神答案, 代码如下:
说一下思路, 把抽象出来的字符串作为key, 只出现一次这样的抽象字符串就存起来, 如果有多个不用字符共享同一个抽象字符, 那么将value设置为空, 表示这个抽象串已经不是unique了。方便判断。
刚开始把共享的字符串们放到set集合里去, 然后判断,看完别人代码发现尼玛真蠢!
HashMap<String, String> map;
public ValidWordAbbr(String[] dictionary) {
map = new HashMap<>();
for(String str : dictionary){
String key = getabs(str);
if(map.containsKey(key)){
if(!map.get(key).equals(str)){
map.put(key, "");
}
}else{
map.put(key, str);
}
}
}
public boolean isUnique(String word) {
String key = getabs(word);
return !map.containsKey(key) || map.get(key).equals(word);
}
private String getabs(String word){
int length =word.length();
return length <= 2 ? word : word.charAt(0) + String.valueOf(length -2) + word.charAt(length-1);
}