LeetCode17 电话字母的组合

LeetCode17 电话字母的组合

题目:

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

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

示例
1
2
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new LinkedList<String>();
if(digits.length() == 0 || digits == ""){

return res;
}
Map<Character,char[]> map = new HashMap<Character, char[]>();
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'});

char[] nums = digits.toCharArray();
int index = 0;

String now = "";
nextDigit(now , index , nums , res , map );

return res ;
}

public void nextDigit(String now , int index ,char[] nums ,List<String> res, Map<Character,char[]> map ){
if(index == nums.length){
res.add(now);
}else{
if (map.containsKey(nums[index])){
for (char c : map.get(nums[index])
) {
nextDigit(now + c , index + 1 , nums , res , map);
}

}
}
}
}
结果
1
2
3
4
5
执行结果:  通过
显示详情
执行用时 : 2 ms, 在所有 Java 提交中击败了74.89%的用户

内存消耗 :35.6 MB, 在所有 Java 提交中击败了78.09%的用户