Monogram phone number
Title Description
题目描述:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Problem-solving ideas
Call recursive loop, each acquiring a first input character string, the character [key] to traverse all characters corresponding to splicing.
As of recursive conditions: input string is cut completely, which is the need to press the End key press
The sample code
public class Test {
//存储最终结果
private static List<String> list = new ArrayList<>();
//保存手机按键,数组的索引代表键位数,内容则为按键对应的数组
private static final String[] KEY_STR = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public static void main(String[] args) {
String numStr = "23";
letterCombinations(numStr);
System.out.println("结果为:" + list);
}
private static void letterCombinations(String numStr) {
callbackMethod("", numStr);
}
private static void callbackMethod(String s, String numStr) {
if ("".equals(numStr)){
list.add(s);
}else {
//记录当前遍历到的数【按键】
int currNum = Integer.parseInt(numStr.substring(0, 1));
//该按键对应的所有字符
String keyCurrStr = KEY_STR[currNum];
char[] keyCurrChars = keyCurrStr.toCharArray();
//遍历该按键的字符
for (int i=0; i<keyCurrStr.length(); i++){
callbackMethod(s + keyCurrChars[i], numStr.substring(1));
}
}
}
}