题目如下
https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
如下代码
是同学写的用的递归,有一点点问题未能正确提交,待修改
package Year2019_July;
import java.util.ArrayList;
import java.util.List;
public class LetterCombinations {
public static void main(String[] args) {
new LetterCombinations().letterCombinations("23");
}
static List<String> result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
char[] two = {'a', 'b', 'c'}, three = {'d', 'e', 'f'}, four = {'g', 'h', 'i'}, five = {'j', 'k', 'l'}, six = {'m', 'n', 'o'}, seven = {'p', 'q', 'r', 's'}, eight = {'t', 'u', 'v'}, nine = {'w', 'x', 'y', 'z'};
char[][] numList = {two, three, four, five, six, seven, eight, nine};
if (digits.equals("")){
return result;
}else{
nextNum(numList, digits, 0, "");
return result;
}
}
public static void nextNum(char[][] numList, String input, int index, String beforeString) {
System.out.println(1);
int num = Integer.parseInt(input.charAt(index++)+"") - 2;
if (num >= 0 && num < 8) {
//2
//{a,b,c}
char[] nowChar = numList[num];
//speed up
StringBuilder[] builders = new StringBuilder[nowChar.length];
for (int i = 0; i < nowChar.length; i++) {
builders[i] = new StringBuilder();
builders[i].append(beforeString);
builders[i].append(nowChar[i]);
if (index == input.length()) {
result.add(builders[i].toString());
} else {
nextNum(numList, input, index, builders[i].toString());
}
}
}
}
}