How to easily beat 99% of Python submissions?!


  • 0
    A

    Here is the easiest and most efficient solution, in Python (No DFS, No Backtracking, No Queues):

    class Solution(object):

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if len(digits) == 0:
            return []
        ans_set = set([""])
        for i in xrange(0, len(digits)):
            temp = []
            for item in ans_set:
                string = item
                temp += self.addLetters(string, digits[i])
            ans_set = temp
        return list(ans_set)
    
    def addLetters(self, string, digit):
        ans = []
        if digit == "2":
            ans = [string+"a", string+"b", string+"c"]
        elif digit == "3":
            ans = [string+"d", string+"e", string+"f"]
        elif digit == "4":
            ans = [string+"g", string+"h", string+"i"]
        elif digit == "5":
            ans = [string+"j", string+"k", string+"l"]
        elif digit == "6":
            ans = [string+"m", string+"n", string+"o"]
        elif digit == "7":
            ans = [string+"p", string+"q", string+"r", string+"s"]
        elif digit == "8":
            ans = [string+"t", string+"u", string+"v"]
        elif digit == "9":
            ans = [string+"w", string+"x", string+"y", string+"z"]
        elif digit == "1":
            ans = [string+"*"]
        elif digit == "0":
            ans = [string+" "]
        return ans

Log in to reply
 

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