The abbreviation of a word is a concatenation of its first letter, the number of…
- User
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 --> d1gbecause there is one letter between the first letter'd'and the last letter'g'.internationalization --> i18nbecause there are 18 letters between the first letter'i'and the last letter'n'.it --> itbecause any word with only two characters is an abbreviation of itself.
Implement the
ValidWordAbbrclass:ValidWordAbbr(String[] dictionary)Initializes the object with adictionaryof words.boolean isUnique(string word)Returnstrueif either of the following conditions are met (otherwise returnsfalse):- There is no word in
dictionarywhose abbreviation is equal toword's abbreviation. - For any word in
dictionarywhose abbreviation is equal toword's abbreviation, that word andwordare the same.
- There is no word in
Example 1:
Input [ "ValidWordAbbr ", "isUnique ", "isUnique ", "isUnique ", "isUnique ", "isUnique "] [[[ "deer ", "door ", "cake ", "card "]], [ "dear "], [ "cart "], [ "cane "], [ "make "], [ "cake "]] Output [null, false, true, false, true, true]
Explanation ValidWordAbbr validWordAbbr = new ValidWordAbbr([ "deer ", "door ", "cake ", "card "]); validWordAbbr.isUnique( "dear "); // return false, dictionary word "deer " and word "dear " have the same abbreviation "d2r " but are not the same. validWordAbbr.isUnique( "cart "); // return true, no words in the dictionary have the abbreviation "c2t ". validWordAbbr.isUnique( "cane "); // return false, dictionary word "cake " and word "cane " have the same abbreviation "c2e " but are not the same. validWordAbbr.isUnique( "make "); // return true, no words in the dictionary have the abbreviation "m2e ". validWordAbbr.isUnique( "cake "); // return true, because "cake " is already in the dictionary and no other word in the dictionary has "c2e " abbreviation.
Constraints:
- Assistantpython
class ValidWordAbbr: def __init__(self, dictionary): self.word_map = {} for word in dictionary: abbr = self.get_abbreviation(word) if abbr not in self.word_map: self.word_map[abbr] = {word} else: self.word_map[abbr].add(word) def isUnique(self, word): abbr = self.get_abbreviation(word) abbr_group = self.word_map.get(abbr, set()) return len(abbr_group) == 0 or (len(abbr_group) == 1 and word in abbr_group) def get_abbreviation(self, word): n = len(word) return word if n <= 2 else word[0] + str(n - 2) + word[-1]