给定一个仅包含数字 2-9 的字符串(类似目前功能机上的键),返回所有它能表示的字母组合。
2---abc
3---def
4---ghi
5---jkl
6---mno
7---pqrs
8---tuv
9---wxyz
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
package com.loo;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class PhoneNumberChar {
public static void main(String[] args) {
String str = "239";
List<String> list = getPhoneNumberChar(str);
for (String s : list) {
System.out.println(s);
}
}
public static List<String> getPhoneNumberChar(String digits) {
List<String> coms = new ArrayList<String>();
if (digits == null || "".equals(digits) || digits.length()==0) {
return coms;
}
Map<Character , String> phoneNumMap = new HashMap<Character , String>();
phoneNumMap.put('2' , "abc");
phoneNumMap.put('3' , "def");
phoneNumMap.put('4' , "ghi");
phoneNumMap.put('5' , "jkl");
phoneNumMap.put('6' , "mno");
phoneNumMap.put('7' , "pqrs");
phoneNumMap.put('8' , "tuv");
phoneNumMap.put('9' , "wxyz");
combinationNum(coms , phoneNumMap , digits , 0 , new StringBuffer());
return coms;
}
public static void combinationNum(List<String> coms , Map<Character , String> phoneNumMap , String digits , int index , StringBuffer combination) {
if (index == digits.length()) {
coms.add(combination.toString());
} else {
char digit = digits.charAt(index);
String phoneNumString = phoneNumMap.get(digit);
int length = phoneNumString.length();
for (int i=0;i<length;i++) {
combination.append(phoneNumString.charAt(i));
combinationNum(coms , phoneNumMap , digits , index+1 , combination);
combination.deleteCharAt(index);
}
}
}
}