题目描述
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
代码
class Solution {
private static Map<Character, String> numberStrs = new HashMap<>();
static {
numberStrs.put('2', "abc");
numberStrs.put('3', "def");
numberStrs.put('4', "ghi");
numberStrs.put('5', "jkl");
numberStrs.put('6', "mno");
numberStrs.put('7', "pqrs");
numberStrs.put('8', "tuv");
numberStrs.put('9', "wxyz");
}
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return result;
}
realLetterCombinations(digits, "", 0, result);
return result;
}
public void realLetterCombinations(String digits, String prefix, int index, List<String> result) {
if (index == digits.length()) {
result.add(prefix);
return;
}
String numberStr = numberStrs.get(digits.charAt(index));
for (int i = 0; i < numberStr.length(); i++ ) {
realLetterCombinations(digits, prefix + numberStr.charAt(i), index + 1, result);
}
}
}
网友评论