Python using reduce() and list comprehension in 56ms


  • 0
    L
    class Solution:
    # @param {string} digits
    # @return {string[]}
    digitDic = {'1':'','2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz','0':''}
    def letterCombinations(self, digits):
        if not digits:
            return []
        n = len(digits)
        if n == 1:
            return [item for item in self.digitDic[digits[0]]]
        return reduce(self.combList,[i for i in digits])
        
    def combList(self, a, b):
        n = len(a)
        if n ==1 and a in self.digitDic:
            a = [i for i in self.digitDic[a]]
        if b in self.digitDic:
            b = [i for i in self.digitDic[b]]
        return [m+n for m in a for n in b]

Log in to reply
 

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