• 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'))
    
  • 相关阅读:
    让你一分钟认识电子身份验证系统EID
    jQuery滑动导航菜单
    sql语句中left join、 inner join的使用
    MySQL数据库分表的3种方法
    Apache 配置多端口 多虚拟主机 局域网访问
    8个开发必备的PHP功能(转)
    CentOS 6.4 图文安装教…
    mysql中char与varchar的区别分析
    PHP+jQuery+Ajax实现用户登录与退…
    隐藏/显示 我的电脑盘符驱动…
  • 原文地址:https://www.cnblogs.com/zzq-123456/p/9818339.html
Copyright © 2020-2023  润新知