LeetCode 笔记十二 九宫格按键的字母组合
程序员文章站
2022-04-02 21:50:07
...
LeetCode 笔记十二 2019/12/26
Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.
大概就是说,我们手机上九宫格按键从2~9分别对应着26个英文字母,我们要做的事情就是,当你按下阿拉伯数字组合时,输出这个组合可能的英文字母组合。
我们来看下他的例子:
example
Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
Code
如果写过之前的题,很显然这道题也自然而然地就会想到用字典的方式去做,以下直接贴代码:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits == '':
return []
digitsDict = {'2':'abc', '3':'def',
'4':'ghi', '5':'jkl', '6':'mno',
'7':'pqrs', '8':'tuv', '9':'wxyz'}
def wordCombine(pres, dicts, digit):
r = []
for p in pres:
for l in dicts[digit]:
r.append(p + l)
return r
results = ['']
for d in digits:
results = wordCombine(results, digitsDict, d)
return results
结果如下:
25 / 25 test cases passed.
Runtime: 24 ms
Memory Usage: 12.7 MB
Runtime: 24 ms, faster than 94.25% of Python3 online submissions for Letter Combinations of a Phone Number.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Letter Combinations of a Phone Number.
上一篇: SqlServer计数器
下一篇: 查询多张表同名字段信息的方法 Java