Letter Combinations of a Phone Number

Letter Combinations of a Phone Number

Binary Search Version - 36ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits: return []
res = ['']
nums = list(digits)
d = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'
], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']}
for n in digits:
lst = d[n]
new_res = []
for char in lst:
for string in res:
new_res.append(string + char)
res = new_res
return res

test code

1
2
3
4
In [347]: s = Solution(); t = s.letterCombinations('23')
In [349]: print(t)
['ad', 'bd', 'cd', 'ae', 'be', 'ce', 'af', 'bf', 'cf']

leet code