题目描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
方法一:回溯
初始化一个字符串,初始值为空,每次取电话号码的一位数字,从哈希表中获得该数字对应的所有字母,并将其中一个字母插入到已有的字母排列后面,然后继续处理电话号码的后一位数字,直到处理完所有数字,然后回退,遍历其他字母组合。
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if(digits.length() == 0){
return res;
}
Map<Integer,String> 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");
back(res,map,digits,0,new StringBuffer());
return res;
}
public void back(List<String> lists,Map<Integer,String> map,String digits,int index,StringBuffer list){
if(index == digits.length()){
lists.add(list.toString());
}else{
String s = map.get(digits.charAt(index)-'0');
int strlen = s.length();
for(int i = 0;i<strlen;i++){
list.append(s.charAt(i));
back(lists,map,digits,index+1,list);
list.deleteCharAt(index);
}
}
}
}
方法二:
举例:“23”
循环遍历字符串“23”:
第一次循环时(“2”):list中依次中添加“2”对应的字母(abc)
此时list为 a,b,c
如果不是第一次循环(“3”),则弹出list中的第一个元素(a),依次在“a"后面添加”3“对应的字母,并添加到list中
此时list为:b,c,ad,ae,af
下一次,弹出b,依次在“b"后面添加”3“对应的字母,并添加到list中
此时list为:c,ad,ae,af,bd,be,bf
下一次,弹出c,依次在“c"后面添加”3“对应的字母,并添加到list中
此时list为:ad,ae,af,bd,be,bf,cd,ce,cf
class Solution {
public List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<String>();
if(digits.length() == 0){
return list;
}
Map<Integer,String> dictionary = new HashMap<>();
dictionary.put(2,"abc");
dictionary.put(3,"def");
dictionary.put(4, "ghi");
dictionary.put(5, "jkl");
dictionary.put(6, "mno");
dictionary.put(7, "pqrs");
dictionary.put(8, "tuv");
dictionary.put(9, "wxyz");
for(int i = 0;i<digits.length();i++){
char c = digits.charAt(i);
String s = dictionary.get(c-'0');
if(i == 0){
for(int j = 0;j<s.length();j++){
list.add(s.substring(j,j+1));
}
}else{
int listSize = list.size();
for(int k = 0;k<listSize;k++){
String old = list.remove(0);
for(int p = 0;p < s.length();p++){
list.add(old+s.substring(p,p+1));
}
}
}
}
return list;
}
}