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
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
方法1:
思路:
在constructor的时候就要把单词都存成hashmap, 那么value是什么呢?如果只对应着缩写对应单词的数量将不能区分door, door和door,deer。前一个是unique,后一个不是。还是要用一个set来记住所有单词,加上set本身有去重的功能,查询的时候只需要返回s.size()。
class ValidWordAbbr {
public:
ValidWordAbbr(vector<string> dictionary) {
for (auto d: dictionary){
if (d.size() < 3){
hash[d].insert(d);
}
else {
string abrev = *d.begin() + to_string(d.size() - 2) + *(d.end() - 1);
hash[abrev].insert(d);
}
}
}
bool isUnique(string word) {
int count = 0;
string abrev;
if (word.size() < 3) {
abrev = word;
}
else {
abrev = *word.begin() + to_string(word.size() - 2) + *(word.end() - 1);
}
for (auto w: hash[abrev]){
if (w != word) count ++;
}
return count == 0;
}
private:
unordered_map<string, set<string>> hash;
};
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr obj = new ValidWordAbbr(dictionary);
* bool param_1 = obj.isUnique(word);
*/
方法2:
思路:
为了压缩空间,同时还能区分同缩写单词是否是同单词,用了"消消乐" 的方法:value只保存unique的单词,如果在construct阶段进来的单词不同,两个词都消掉,设为“”。注意这个设置是有讲究的:它保证了count != 0, 同时又unqualified both。保证count != 0是因为,之后的isValid可能会询问之前不存在的缩写,应该算作unique。
易错点
- 消掉并恢复“”
- 自己不应该消掉自己:[“a”, “a”],“a” is still unique。
- isValid要检查未出现过的缩写
class ValidWordAbbr {
public:
ValidWordAbbr(vector<string> dictionary) {
for (auto d: dictionary){
string abrev;
if (d.size() < 3){
abrev = d;
}
else {
abrev= *d.begin() + to_string(d.size() - 2) + *(d.end() - 1);
}
if (hash.count(abrev) == 0 || hash[abrev] == d) {
hash[abrev] = d;
}
else {
hash[abrev] = "";
}
}
}
bool isUnique(string word) {
string abrev;
if (word.size() < 3) {
abrev = word;
}
else {
abrev = *word.begin() + to_string(word.size() - 2) + *(word.end() - 1);
}
return hash.count(abrev) == 0 || hash[abrev] == word;
}
private:
unordered_map<string, string> hash;
};
/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr obj = new ValidWordAbbr(dictionary);
* bool param_1 = obj.isUnique(word);
*/