Tuesday, April 22, 2014

Leetcode (Python): Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

Solution:

class Solution:
    # @return a list of strings, [s1, s2]
    def letterCombinations(self, digits):
        solution = [""]
        for i in range(0,len(digits)):
            tempList =[];
            for string in solution:
                if digits[i]=='2':
                    tempList.append(string+"a")
                    tempList.append(string+"b")
                    tempList.append(string+"c")
                elif digits[i]=='3':
                    tempList.append(string+"d")
                    tempList.append(string+"e")
                    tempList.append(string+"f")
                elif digits[i]=='4':
                    tempList.append(string+"g")
                    tempList.append(string+"h")
                    tempList.append(string+"i")
                elif digits[i]=='5':
                    tempList.append(string+"j")
                    tempList.append(string+"k")
                    tempList.append(string+"l")
                elif digits[i]=='6':
                    tempList.append(string+"m")
                    tempList.append(string+"n")
                    tempList.append(string+"o")
                elif digits[i]=='7':
                    tempList.append(string+"p")
                    tempList.append(string+"q")
                    tempList.append(string+"r")
                    tempList.append(string+"s")
                elif digits[i]=='8':
                    tempList.append(string+"t")
                    tempList.append(string+"u")
                    tempList.append(string+"v")
                elif digits[i]=='9':
                    tempList.append(string+"w")
                    tempList.append(string+"x")
                    tempList.append(string+"y")
                    tempList.append(string+"z")
            solution = tempList
        return solution

No comments :

Post a Comment