1.题目描述
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"].
2.题目分析
注意含有“0”“1”就返回空列表
3.解题思路
1 class Solution(object): 2 def letterCombinations(self, digits): 3 """ 4 :type digits: str 5 :rtype: List[str] 6 """ 7 strs="" #当前字符串 8 temp=[] #当前字符串列表 9 result=[] #最后要返回的结果 10 dic={"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"} #设置字典便于查询 11 if "1"in digits or"0"in digits: #排除含有“0”“1”的情况 12 return [] 13 for i in digits: 14 temp=result #将上一级字符串列表给temp 15 result=[] #result列表清空 16 l1=len(temp) 17 str1=dic[i] 18 l2=len(str1) 19 j=0 20 if l1==0: #得到第一级字符串列表 21 for s in str1: 22 result.append(s) 23 while j<l1: 24 k=0 25 while k<l2: 26 strs=temp[j] #获得当前字符串 27 strs+=str1[k] 28 result.append(strs) #补充result列表 29 k+=1 30 j+=1 31 return result