LeetCode--017--电话号码的字母组合(java)

时间:2023-12-13 12:17:26

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

LeetCode--017--电话号码的字母组合(java)

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
转自:https://blog.csdn.net/xushiyu1996818/article/details/84334799
class Solution {
HashMap<Character,char[]> map = new HashMap<>();
List<String> result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
int length = digits.length();
if(length == 0){
return result;
}
map.put('2',new char[]{'a','b','c'});
map.put('3', new char[]{'d','e','f'});
map.put('4', new char[]{'g','h','i'});
map.put('5', new char[]{'j','k','l'});
map.put('6', new char[]{'m','n','o'});
map.put('7', new char[]{'p','q','r','s'});
map.put('8', new char[]{'t','u','v'});
map.put('9', new char[]{'w','x','y','z'});
combine("",digits);
return result;
}
public void combine(String nowStr,String remain){
int length = remain.length();
if(length == 0){
result.add(nowStr);
return;
}
Character now = remain.charAt(0);
for(char nowChar:map.get(now)){
combine(nowStr+nowChar,remain.substring(1));
}
} }

2019-04-15 22:48:47

23  => ["ad","bd","cd","ae","be","ce","af","bf","cf"]

234=> ["adg","bdg","cdg","aeg","beg","ceg","afg","bfg","cfg","adh"。。。。。。]

 class Solution:
def letterCombinations(self, digits):
self.dict = {"":"abc", "":"def", "":"ghi", "":"jkl", "":"mno", "":"pqrs","":"tuv","":"wxyz"}
if digits == "":
return []
result = [""]
for digit in digits:
strs = self.dict[digit]
curResult = []
for char in strs:
for res in result:
curResult.append(res+char)
result = curResult
return result

2019-11-28 14:13:09