An abbreviation of a word follows the form <first letter><number><last letter>. 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或者2的字符串不是abbreviation的,我以为直接输出False,但是Test case直接给了True。
这句话很关键,A word's abbreviation is unique ifno other word from the dictionary has the same abbreviation. 因为是no other word,所以如果有hello在字典里,如果你判断的词也是hello,那么是同样的word,不是other word,应该返回True。
class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str]
"""
self.dic = {} # 空字典
for word in dictionary:
abb = word if len(word) <= 2 else word[0] + str(len(word) - 2) + word[-1]
# 如果词长度小于等于2,就是这个词本身存入字典,否则遵循abbreviation规则
self.dic[abb] = word if abb not in self.dic else "" if self.dic[abb] != word else self.dic[abb]
# 1. 如果abbreviation之后的词不在字典中,直接存入
# 2. 如果童谣的abbreviation结果已经存在了,但是value的词不是同一个,即abbreviation之后对应多个词,那么直接把value存为""。因为这样的abbreviation不符合no other word这个条件,肯定会返回False。
# 3. abbreviation对应的已经在字典中的本身value
def isUnique(self, word):
"""
check if a word is unique.
:type word: str
:rtype: bool
"""
abb = word if len(word) <= 2 else word[0] + str(len(word) - 2) + word[-1]
return abb not in self.dic or self.dic[abb] == word
# 因为abbreviation对应多个词的可能性我们已经给了""的value,所以可以直接判断
# 1. 不在字典中
# 2. 在字典中,且刚好是同一个词
Tip: 这里的条件,no other word很有用,因为能推导出如果有一个abbreviation之后的key,对应了多个value,那么我们能不存一个list的value,而直接把这个对应的value给予一个固定的值。代码更简单,快捷。避免使用append,或者+,等操作。