Simple Python Solution with Explanation


  • 16
    M
    class Solution(object):
        def generateAbbreviations(self, word):
            """
            :type word: str
            :rtype: List[str]
            """
            def helper(word, pos, cur, count, result):
                if len(word) == pos:
                    # Once we reach the end, append current to the result
                    result.append(cur + str(count) if count > 0 else cur)
                else:
                    # Skip current position, and increment count
                    helper(word, pos + 1, cur, count + 1, result)
                    # Include current position, and zero-out count
                    helper(word, pos + 1, cur + (str(count) if count > 0 else '') + word[pos], 0, result)
    
            result = []
            helper(word, 0, '', 0, result)
            return result

  • 0

    This is absolutely beautiful! Pleas take me knees!


  • 0
    G

    Thank you, it is genius.


  • 0
    S

    Awesome! Very intuitive and concise solution.


Log in to reply
 

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