• 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'))
    
  • 相关阅读:
    一周内签到连续天数求解
    int型动态数组总结
    快速排序总结
    希尔排序总结
    冒泡排序的总结
    桶排序总结
    插入排序的总结
    选择排序的总结
    二分法的五种实现
    安装Yum源
  • 原文地址:https://www.cnblogs.com/zzq-123456/p/9818339.html
Copyright © 2020-2023  润新知