You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.0 KiB

2 years ago
package class28;
import java.util.ArrayList;
import java.util.List;
public class Problem_0017_LetterCombinationsOfAPhoneNumber {
public static char[][] phone = {
{ 'a', 'b', 'c' }, // 2 0
{ 'd', 'e', 'f' }, // 3 1
{ 'g', 'h', 'i' }, // 4 2
{ 'j', 'k', 'l' }, // 5 3
{ 'm', 'n', 'o' }, // 6
{ 'p', 'q', 'r', 's' }, // 7
{ 't', 'u', 'v' }, // 8
{ 'w', 'x', 'y', 'z' }, // 9
};
// "23"
public static List<String> letterCombinations(String digits) {
List<String> ans = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return ans;
}
char[] str = digits.toCharArray();
char[] path = new char[str.length];
process(str, 0, path, ans);
return ans;
}
public static void process(char[] str, int index, char[] path, List<String> ans) {
if (index == str.length) {
ans.add(String.valueOf(path));
} else {
char[] cands = phone[str[index] - '2'];
for (char cur : cands) {
path[index] = cur;
process(str, index + 1, path, ans);
}
}
}
}