[LeetCode] Unique Word Abbreviation

288. Unique Word Abbreviation

The abbreviation of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an abbreviation of itself.

For example:

  • dog —> d1g because there is one letter between the first letter ‘d’ and the last letter ‘g’.
  • internationalization —> i18n because there are 18 letters between the first letter ‘i’ and the last letter ‘n’.
  • it —> it because any word with only two characters is an abbreviation of itself.

Implement the ValidWordAbbr class:

  • ValidWordAbbr(String[] dictionary) Initializes the object with a dictionary of words.
  • boolean isUnique(string word) Returns true if either of the following conditions are met (otherwise returns false):
    • There is no word in dictionary whose abbreviation is equal to word’s abbreviation.
    • For any word in dictionary whose abbreviation is equal to word’s abbreviation, that word and word are the same.
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
class ValidWordAbbr {
private:
unordered_map<string, set<string>> words;

private:
string getAbbreviation(string word) {
return word.length() <= 2 ? word : word[0] + to_string(word.length() - 2) + word[word.length() - 1];
}
public:
ValidWordAbbr(vector<string>& dictionary) {
for(string word : dictionary) {
string abbreviation = getAbbreviation(word);
auto it = words.find(abbreviation);
if(it == words.end()) {
words.insert(make_pair(abbreviation, set<string> {word}));
} else {
it->second.insert(word);
}
}
}

bool isUnique(string word) {
auto it = words.find(getAbbreviation(word));
return it == words.end() || (*(it->second.begin()) == word && it->second.size() == 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/15/PS/LeetCode/unique-word-abbreviation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.