AC Python solution


  • 12
    X
    class Solution:
        # @return a list of strings, [s1, s2]
        def letterCombinations(self, digits):
            self.dict = {"1":"", "2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs","8":"tuv","9":"wxyz","10":" "}
            result = [""]
            for digit in digits:
                lst = self.dict[digit]
                newresult = []
                for char in lst:
                    for str in result:
                        newresult.append(str+char)
                result = newresult
            return result

  • 1
    D

    You can use list as map directly, and there will not be "10" as input, only 1 or 0

    self.dict = [' ', ' ', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']

  • 1
    H

    @xiaoying10101 str has special meaning in python


  • 2

    Same idea but clearer code:

    d2a = { '1': '',    '2': 'abc', '3': 'def',
            '4': 'ghi', '5': 'jkl', '6': 'mno',
            '7': 'pqrs','8': 'tuv', '9': 'wxyz',
            '0': ' '}
    
    class Solution(object):
        def letterCombinations(self, digits):
            ans = [''] if digits else []
            for d in digits:
                ans = [r+e for e in d2a[d] for r in ans]
            return ans
    
    

Log in to reply
 

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