Visualization


  • 6

  • 0
    S

    This deserves many upvotes!

    Code for this visualization -

    class Solution(object):
        def wordsAbbreviation(self, words):
            """
            :type dict: List[str]
            :rtype: List[str]
            """
            def get_abbreviation(word,old_abbreviation):
                if old_abbreviation == '':
                    abbreviation = word[0] + str(len(word[1:-1])) + word[-1]                
                else:
                    for i in range(len(old_abbreviation)):
                        if old_abbreviation[i].isdigit():
                            abbreviation = word[:i+1] + str(len(word[i+1:-1])) + word[-1]
                            break
                if len(word) <= len(abbreviation):
                    abbreviation = word
                return abbreviation
            
            
            abbreviations = [''] * len(words)
            duplicates    = collections.defaultdict(list)
            for i,word in enumerate(words):
                abbreviations[i] = get_abbreviation(word,'')
                duplicates[abbreviations[i]] += i,
            
            for i in range(len(abbreviations)):
                if len(duplicates[abbreviations[i]]) == 1:
                    continue
                else:
                    while len(duplicates[abbreviations[i]]) > 1:
                        for index in duplicates[abbreviations[i]]:
                            abbreviation = get_abbreviation(words[index], abbreviations[index])
                            abbreviations[index] = abbreviation
                            duplicates[abbreviation] += index,
                            
            return abbreviations
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.