leetcode-288. Unique Word Abbreviation

An abbreviation of a word follows the form . Below are some examples of word abbreviations:
a) it –> it (no abbreviation)
b) d|o|g –> d1g
c) i|nternationalizatio|n –> i18n
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
原题地址

一道easy题,然而并不是很easy。思路很明确,用hashtable记下字典里的缩写,然后比较所给的单词。有一个细节是,如果所给的词在字典里有,并且这个词的缩写在字典的缩写里是唯一的,是要返回true的。直接的解决办法是在hashtable里记下缩写对应的每个单词或者他们的index,但是在网上看到了更好的办法。只需要存一个string,如果有不同单词对应一个缩写就把这个string设为空。代码如下:

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
class ValidWordAbbr {
unordered_map<string, string> hashmap;
public:
ValidWordAbbr(vector<string> &dictionary) {
for (string& s : dictionary) {
string abbr = toAbbr(s);
if (hashmap.count(abbr) > 0 && hashmap[abbr] != s)
hashmap[abbr] = "";
else
hashmap[abbr] = s;
}
}
string toAbbr(string word) {
if (word.size() <= 2)
return word;
return word[0] + to_string(word.size() - 2) + word.back();
}
bool isUnique(string word) {
string abbr = toAbbr(word);
if (hashmap.count(abbr) == 0 || hashmap[abbr] == word)
return true;
return false;
}
};
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa(dictionary);
// vwa.isUnique("hello");
// vwa.isUnique("anotherWord");