标签:type png input letter 元素 possible alt ping bsp
题目:
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
标签:type png input letter 元素 possible alt ping bsp
原文地址:http://www.cnblogs.com/yuanzhaoyi/p/6062812.html