Letter Combinations of a Phone Number
A mapping of digit to letters (just like on the telephone buttons) is given below.
![](http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png)
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 class Solution {
//保存为静态变量,效率更高
public static String[] map = new String[128];
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<String>();
char[] ch = digits.toCharArray();
if(ch.length == 0)
return list;
//按ACSII码保存
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";
for(int i = 0; i < ch.length; i++){
list = addList(ch[i],list);
}
return list;
}
//将每个数字对应的字符与list相加后返回
public static List<String> addList(char c,List<String> list){
String s = map[c];//读取对应字符串
if(list.size() == 0){//如果是第一个字符串
for(int i = 0; i < s.length();i++){
list.add(s.charAt(i) + "");
}
return list;
}
else{//不是则循环相加
List<String> al = new ArrayList<String>();
for(int i = 0; i < s.length();i++){
for(int j = 0; j < list.size(); j++){
al.add(list.get(j) + s.charAt(i));
}
}
return al;
}
}
}