Word Abbreviation – Python 3 (Week 12 – 02)

class Solution:
    """
    @param dict: an array of n distinct non-empty strings
    @return: an array of minimal possible abbreviations for every word
    """
    def wordsAbbreviation(self, dict):
        # write your code here
        if not dict:
            return []
        ans = [''] * len(dict)
        count = {}
        r = 1 ## round
        for i in range(len(dict)):
            ans[i] = (self.getAbbr(dict[i], r))
            count[ans[i]] = count.get(ans[i],0) + 1
            
        while True:
            r += 1
            unique = True 
            for i in range(len(dict)):
                if count[ans[i]] > 1:
                    ans[i] = self.getAbbr(dict[i], r)
                    count[ans[i]] = count.get(ans[i],0) + 1
                    unique = False
            if unique:
                break

        return ans
        
        
        
        
        
    def getAbbr(self, s, p): ## p is prefix, round
        if len(s) < 3 + p:
            return s
        return s[:p] + str(len(s) - 1 - p) + s[- 1]

Leave a comment

Design a site like this with WordPress.com
Get started