共计 734 个字符,预计需要花费 2 分钟才能阅读完成。
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.
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if digits=='':
return []
digit_to_str={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
result=['']
for x in digits:
tmp=[]
for y in result:
for z in digit_to_str[x]:
tmp.append(y+z)
result=tmp
return result
对比优秀解法
class Solution:
# @return a list of strings, [s1, s2]
def letterCombinations(self, digits):
if '' == digits: return []
kvmaps = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
正文完
请博主喝杯咖啡吧!