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”].
题意:九键输入法,有多少可能的字符串输出
代码解析:方法一:用迭代的思想,每一次把新的字符加入到已有的字符串上去再回溯到上一层
方法二耗时比较长,思想也是迭代,但是没有回溯
public class Solution3 {
public List letterCombinations(String digits) {
List result=new ArrayList();
StringBuffer sb=new StringBuffer();
int value=digits.length()-1;
if(digits.length()==0) {
return result;
}
letterCombinationsHelper(result,sb,0,value,digits);
return result;
}
public void letterCombinationsHelper(List<String> result,StringBuffer sb,int index,int max,String digits)
{
if(index>max)
{
result.add(new String(sb.toString()));
return;
}
char c=digits.charAt(index);
char start='a';
char end='c';
/* map character from phone number to alphabet*/
switch(c)
{
case '2':
start='a';
end='c';
break;
case '3':
start='d';
end='f';
break;
case '4':
start='g';
end='i';
break;
case '5':
start='j';
end='l';
break;
case '6':
start='m';
end='o';
break;
case '7':
start='p';
end='s';
break;
case '8':
start='t';
end='v';
break;
case '9':
start='w';
end= 'z';
break;
}
/*iterate over all the character mapping and back track*/
for(char val=start;val<=end;val++)
{
sb.append(val);
letterCombinationsHelper(result,sb,index+1,max,digits);
sb.deleteCharAt(sb.length()-1);
}
}
}
方法二
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
int n = digits.length();
if(n < 1) return result;
result.add("");
for(int i = 0; i < n; i++)
{
char c = digits.charAt(i);
if(!dict.containsKey(c)) return new ArrayList<String>();
String s = dict.get(c);
List<String> temp = new ArrayList<String>();
for(String element : result)
{
for(char extra : s.toCharArray())
{
temp.add(element + extra);
}
}
result = temp;
}
return result;
}
private static Map<Character,String> dict;
static
{
dict = new HashMap<Character, String>();
dict.put('2', "abc");
dict.put('3', "def");
dict.put('4', "ghi");
dict.put('5', "jkl");
dict.put('6', "mno");
dict.put('7', "pqrs");
dict.put('8', "tuv");
dict.put('9', "wxyz");
}
}