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.
Subscribe to see which companies asked this question
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Mouse
*
*/
public class Solution {
public static List<String> letterCombinations2(String digits) {
List<String> result = new ArrayList<String>();
if (digits.isEmpty()) {
result.add("");
return result;
}
String[] map = new String[10];
map[0] = null;
map[1] = null;
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;
}
public static void main(String[] args) {
String a = "";
List<String> b = letterCombinations2(a);
System.out.println(b);
}
}
http://blog.csdn.net/china_wanglong/article/details/38495355