Unique Abbreviation
题目描述
An abbreviation of a word follows the form
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
解题方法
Solution
class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str]
"""
self.dic = {}
for word in dictionary:
abbr = self.getAbbr(word)
if abbr == word:
continue
if abbr in self.dic:
self.dic[abbr] = False
else:
self.dic[abbr] = word
def isUnique(self, word):
"""
check if a word is unique.
:type word: str
:rtype: bool
"""
if not word:
return True
abbr = self.getAbbr(word)
return (abbr not in self.dic) or (self.dic[abbr] == word)
def getAbbr(self, word):
abbr = ""
if len(word) <= 2:
abbr = word
else:
abbr = word[0] + str(len(word) - 2) + word[-1]
return abbr