Question:
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
Answer:
class Solution {
public List<String> letterCombinations(String digits) {
List<String> tmp = new ArrayList<>();
List<String> result = new ArrayList<>();
Map map = new HashMap();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
if (digits != null && digits.length() > 0) {
char[] numbers = digits.toCharArray();
for (char c : map.get(numbers[0]).toString().toCharArray()) {
result.add(String.valueOf(c));
}
for (int i = 1; i < numbers.length; i++) {
tmp.clear();
tmp.addAll(result);
result.clear();
String shouldAdd = map.get(numbers[i]).toString();
for (String s : tmp) {
for (char c1 : shouldAdd.toCharArray()) {
result.add(s + String.valueOf(c1));
}
}
}
}
return result;
}
}
此用例运行花时5ms;顺手贴一下运行耗时1ms大佬的解法;
class Solution {
String[] codes = new String[]{"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public List<String> letterCombinations(String digits) {
if(digits == null || digits.equals("")){
return new ArrayList<>();
}
List<String> result = new ArrayList<>();
backtrace(digits, result, "", 1, digits.length());
return result;
}
private void backtrace(String digits, List<String> list, String str, int deep, int n){
if(deep == n){
for(char c : codes[digits.charAt(deep-1) - '0' -2].toCharArray()){
list.add(str+c);
}
}else{
for(char c : codes[digits.charAt(deep-1) - '0' -2].toCharArray()){
backtrace(digits, list, str+c, deep+1, n);
}
}
}
}