Divide and Conquer concise python code


  • 0
    J
    class Solution(object):
    def generateAbbreviations(self, word):
        """
        :type word: str
        :rtype: List[str]
        """
        if len(word) == 0:return [ '' ]
        if len(word) == 1:return ['1', word[0]]
        
        l = 0; r = len(word)
        res = []
        mid = (l+r)/2
        words1 = self.generateAbbreviations(word[:mid])
        words2 = self.generateAbbreviations(word[mid:])
        for word1 in words1:
            for word2 in words2:
                res.append(self.combine(word1, word2))
        return res
    
        
    def combine(self, word1, word2):
        if self.isNum(word1[-1]) and self.isNum(word2[0]):
            return word1[:-1] + str( int(word1[-1]) + int(word2[0]) )+word2[1:]
        else:
            return word1 + word2
    
    def isNum(self, c):
        return c >= '0' and c <= '9'

Log in to reply
 

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