17. Letter Combinations of a Phone Number
题目描述
类似于9键拼音输入法,将数字对应的所有可能的字母组合都列出来。
1. 建立数字-字母映射字典
2. 初始化ans,包含一个空字符串
3.判断特殊情况:数字串为空
4.遍历数字串中的每个数字:
使用列表t保存历史计算结果,本次循环中需要在历史计算结果之后+字符;
清空答案列表ans,本次循环中加入重新计算的最长字符串;
两层循环遍历字符,将其连接+之后加入答案列表ans
完整代码
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
letmap={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
ans=['']
if not digits: #数字串为空的特殊情况
return []
for d in digits:
t=ans #t记录之前数字对应字母的组合情况
ans=[]
for l in letmap[d]: #两层循环组合字符
for s in t:
ans.append(s+l)
return ans