给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = ""
输出:[]
示例 3:
输入:digits = "2"
输出:["a","b","c"]
提示:
0 <= digits.length <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。
解题思路
1、先将题目所示的键盘放入一张HashMap中
maps.put('2', "abc");
maps.put('3', "def");
maps.put('4', "ghi");
maps.put('5', "jkl");
maps.put('6', "mno");
maps.put('7', "pqrs");
maps.put('8', "tuv");
maps.put('9', "wxyz");
2、准备一个列表strings存放上一步所有的可能性。
3、当前字符组合的可能性等于上一部所有的可能性 * 当前步骤所有的可能性。
Java代码:
class Solution {
public List<String> letterCombinations(String digits) {
HashMap<Character, String> maps = new HashMap<>();
maps.put('2', "abc");
maps.put('3', "def");
maps.put('4', "ghi");
maps.put('5', "jkl");
maps.put('6', "mno");
maps.put('7', "pqrs");
maps.put('8', "tuv");
maps.put('9', "wxyz");
List<String> strings = new ArrayList<>();
List<String> temp = new ArrayList<>();
for(int i=0; i<digits.length(); i++){
if(i==0){
char c = digits.charAt(i);
for(char cur:maps.get(c).toCharArray()){
temp.add(String.valueOf(cur));
}
}else{
char c = digits.charAt(i);
for(String string:strings){
for(char cur:maps.get(c).toCharArray()){
temp.add(string + String.valueOf(cur));
}
}
}
strings.clear();
strings.addAll(temp);
temp.clear();
}
return strings;
}
}
Python代码
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
maps = {}
maps['2'] = 'abc'
maps['3'] = 'def'
maps['4'] = 'ghi'
maps['5'] = 'jkl'
maps['6'] = 'mno'
maps['7'] = 'pqrs'
maps['8'] = 'tuv'
maps['9'] = 'wxyz'
strings = []
temp = []
for i in range(len(digits)):
if i == 0:
c = digits[i]
for cur in maps[c]:
temp.append(cur)
else:
c = digits[i]
for string in strings:
for cur in maps[c]:
temp.append(string + cur)
strings = temp[:]
temp = []
return strings