原题:
Given a digit string, 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.
Input:Digit string "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.
解法一:
对数字进行解析,相当于遍历一棵树,可以使用数的遍历算法
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
String[] map = new String[10];
map[0] = "";
map[1] = "";
map[2] = "abc";
map[3] = "def";
map[4] = "ghi";
map[5] = "jkl";
map[6] = "mno";
map[7] = "pqrs";
map[8] = "tuv";
map[9] = "wxyz";
char[] middleTemp = new char[digits.length()];
dfsGetStr(digits, 0, middleTemp, map, result);
return result;
}
private void dfsGetStr(String digits,int index,
char[] middleStr, String[] map, List<String> result) {
if(index == digits.length()) {
result.add(new String(middleStr));
return ;
}
char strChar = digits.charAt(index);
for(int i=0; i<map[strChar-'0'].length(); i++) {
middleStr[index] = map[strChar-'0'].charAt(i);
dfsGetStr(digits, index+1, middleStr, map, result);
}
}
解法二:
直接使用循环求解
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if(digits.isEmpty()) {
result.add("");
return result;
}
String[] map = new String[10];
map[0] = "";
map[1] = "";
map[2] = "abc";
map[3] = "def";
map[4] = "ghi";
map[5] = "jkl";
map[6] = "mno";
map[7] = "pqrs";
map[8] = "tuv";
map[9] = "wxyz";
int[] number = new int[digits.length()]; //存储digits中每个字符在循环中的编号,初始为0
int k = digits.length()-1;
while(k>=0) {
k = digits.length()-1;
char[] charTemp = new char[digits.length()];
for(int i=0; i<digits.length(); i++) {
charTemp[i] = map[digits.charAt(i)-'0'].charAt(number[i]);
}
result.add(new String(charTemp));
while(k>=0) {
if( number[k] < (map[digits.charAt(k)-'0'].length()-1) ) {
number[k]++;
break;
} else {
number[k] = 0;
k--;
}
}
}
return result;
}