Leetcode题库——17.电话号码的字母组合


@author: ZZQ
@software: PyCharm
@file: letterCombinations.py
@time: 2018/10/18 18:33
要求:给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
2:abc; 3: def; 4:ghi; 5: jkl; 6: mno; 7: pqrs; 8: tuv; 9: wxyz
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路:先得出每隔数字代表的字母,然后两两合并再合并。(记录奇偶)

class Solution():
    def __init__(self):
        pass

    def numToLetter(self, num):
        dict = {2: 'abc',
                3: 'def',
                4: "ghi",
                5: "jkl",
                6: "mno",
                7: "pqrs",
                8: "tuv",
                9: "wxyz"
                }
        return dict[num]

    def combine(self, str1, str2):
        len1 = len(str1)
        len2 = len(str2)
        combined = []
        temp_str = ''
        for i in range(len1):
            for j in range(len2):
                combined.append(temp_str+str1[i]+str2[j])
            temp_str = ''
        return combined

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if digits == "":
            return []
        length = len(digits)
        letters = []
        for i in range(length):
            cur_num = int(digits[i])
            cur_letter = self.numToLetter(cur_num)
            letters.append(cur_letter)
        if len(letters) == 1:
            return [letters[0][t] for t in range(len(letters[0]))]
        while len(letters) > 1:
            cur_letters = []
            if len(letters) % 2:
                for i in range((len(letters) - 1) / 2):
                    cur_letters.append(self.combine(letters[i * 2], letters[i * 2 + 1]))
                cur_letters.append(letters[len(letters)-1])
            else:
                for i in range(len(letters) / 2):
                    cur_letters.append(self.combine(letters[i * 2], letters[i * 2 + 1]))
            letters = cur_letters
        return letters[0]


if __name__ == "__main__":
    answer = Solution()
    print answer.letterCombinations('2')
    # print len(answer.letterCombinations('2345'))
posted @ 2018-10-19 19:25  恩zzq我是  阅读(270)  评论(0编辑  收藏  举报