288. Unique Word Abbreviation

An abbreviation of a word follows the form . Below are some examples of word abbreviations:

1
2
3
4
5
6
7
8
9
10
11
12
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
Given dictionary = [ "deer", "door", "cake", "card" ]
isUnique("dear") ->
false
isUnique("cart") ->
true
isUnique("cane") ->
false
isUnique("make") ->
true

解法1:

莫名其妙的一题。。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class ValidWordAbbr {
HashMap<String, Integer> map = null;
HashMap<String, Integer> countMap = null;
public ValidWordAbbr(String[] dictionary) {
map = new HashMap<>();
countMap = new HashMap<>();
for (String str : dictionary) {
String abbr = getAbbr(str);
map.put(abbr, map.getOrDefault(abbr, 0) + 1);
countMap.put(str, countMap.getOrDefault(str, 0) + 1);
}
}
private String getAbbr(String str) {
if (str.length() <= 2) {
return str;
}
return str.substring(0, 1) + Integer.toString(str.length() - 2) + str.substring(str.length() - 1, str.length());
}
public boolean isUnique(String word) {
String key = getAbbr(word);
int abbrCount = map.getOrDefault(key, 0);
int count = countMap.getOrDefault(word, 0);
return abbrCount <= count;
}
}
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr obj = new ValidWordAbbr(dictionary);
* boolean param_1 = obj.isUnique(word);
*/