The following questions
https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
Given a string contains only numeric characters 2-9, it can return all letter combinations indicated.
Given digital map to letters as follows (the same telephone key). Note 1 does not correspond to any alphabet.
Example:
Input: "23"
outputs:. [ "Ad", " ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Description:
Although the above the answer is based on lexicographic order, but you can choose the order of the answer output.
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/letter-combinations-of-a-phone-number
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
The following code
Students are used to write recursive, there is a little problem failed to submit correct, to be modified
package Year2019_July;
java.util.ArrayList import;
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());
}
}
}
}
}