zoukankan      html  css  js  c++  java
  • 17. 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.

    代码:

    每日一题哦,今天做到这个题目,仔细一看,就会找到数字对应的字符串,然后把字符串组合起来,返回一个列表。

    想想就不应该很复杂,可是,还是做了一个小时,唉,看来必须每天坚持练习练习!

    逻辑很简单,就是用一个列表保存每次两个字符串相加的结果,从digits的第一个元素开始,不断和下一次相加,一直加到digits最后一位元素:

        def letterCombinations(self, digits):
            """
            :type digits: str
            :rtype: List[str]
            """
            letter_dic = {2:"abc",3:"def",4:"ghi",5:"jkl",6:"mno",7:"pqrs",8:"tuv",9:"wxyz"}
            if len(digits)==0:return []
            res_list = [list(letter_dic[int(digits[0])])]
            digits = digits[1:]
            while len(digits) !=0:                
                res_list.append(self.str_connect(res_list[-1],list(letter_dic[int(digits[0])])))       
                digits = digits[1:]
                #print (res_list)
            return res_list[-1]
        
        def str_connect(self,str_ori,str_add):
            res = []
            for i in range(0,len(str_ori)):
                for j in str_add:
                    res.append(str_ori[i]+j)
            return res
           

  • 相关阅读:
    丑数系列
    452. 用最少数量的箭引爆气球
    406. 根据身高重建队列
    763. 划分字母区间
    所有二叉树题目记录
    二叉树前中后序遍历非递归(迭代)解法
    二叉树的层序遍历题目汇总
    442. 数组中重复的数据&&448. 找到所有数组中消失的数字
    225. 用队列实现栈(Easy)
    使用ClosedXML读写excel
  • 原文地址:https://www.cnblogs.com/yuanzhaoyi/p/6062812.html
Copyright © 2011-2022 走看看