Unique Word Abbreviation – Python 3 (Week 12 – 03)

class ValidWordAbbr:
    """
    @param: dictionary: a list of words
    """
    def __init__(self, dictionary):
        # do intialization if necessary
        self.dictCnt = collections.Counter(dictionary)
        self.abbCnt = collections.Counter([self.getAbbr(word) for word in dictionary])


    """
    @param: word: a string
    @return: true if its abbreviation is unique or false
    """
    def isUnique(self, word):
        # write your code here
        return self.dictCnt.get(word, 0) == self.abbCnt.get(self.getAbbr(word), 0)


    def getAbbr(self, word):
        if len(word) < 3:
            return word
        return word[0] + str(len(word) - 2) + word[-1]
        

Time O(1). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started