题目地址:Letter Combinations of a Phone Number - LeetCode
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.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
这道题目是2019-9-16的XX笔试题,可惜自己没有早点做到。
题目是简单的。
Python解法如下:
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
s = {
'1': '', '2': ['a', 'b', 'c'], '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
}
res = ['']
if digits == '':
return []
for i in digits:
temp = []
for j in res:
for k in s[i]:
temp.append(j+k)
res = temp
return res
看到别人的一行解法如下:
from functools import reduce
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
s = {
'1': '', '2': ['a', 'b', 'c'], '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
}
if digits=='': return []
return reduce(lambda acc, digit: [x + y for x in acc for y in s[digit]], digits, [''])
C++解法如下:
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
if (digits.empty()) {
return result;
}
string charmap[10] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
result.emplace_back("");
for (char digit : digits) {
vector<string> temp;
string chars = charmap[digit - '0'];
for (const auto &j : result) {
for (char c : chars) {
temp.push_back(j + c);
}
}
result = temp;
}
return result;
}
};