边工作边刷题:70天一遍leetcode: day 88

Unique Word Abbreviation
要点:

  • 简单题,主要是理解题意。no other words have the same abbreviation as the given word意思就是如果没有同样的abbrev或者有但是只由dict中相同的word产生。
  • 可以用True/False表示unique,同时用set来保存哪个word产生的abbrev

https://repl.it/CnNt

# 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


class ValidWordAbbr(object):
    def __init__(self, dictionary):
        """
        initialize your data structure here.
        :type dictionary: List[str]
        """
        self.countmap = {}
        self.words = set(dictionary)
        
        for w in self.words:
            abw = self.getAbbre(w)
            self.countmap[abw]=True if abw not in self.countmap else False

    def isUnique(self, word):
        """
        check if a word is unique.
        :type word: str
        :rtype: bool
        """
        w = self.getAbbre(word)
        return w not in self.countmap or (self.countmap[w] and word in self.words)
        
    def getAbbre(self, word):
        n = len(word)
        if n<=2: return word
        return word[0]+str(n-2)+word[n-1]

# Your ValidWordAbbr object will be instantiated and called as such:
# vwa = ValidWordAbbr(dictionary)
# vwa.isUnique("word")
# vwa.isUnique("anotherWord")
posted @ 2016-07-19 20:03  absolute100  阅读(121)  评论(0编辑  收藏  举报