17. Letter Combinations of a Phone Number
Posted PolarBearInterest
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于17. Letter Combinations of a Phone Number的主要内容,如果未能解决你的问题,请参考以下文章
17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number