/电话号码对应的字符组合:在电话或者手机上,一个数字如2对应着字母ABC,7对应着
PQRS。那么数字串27所对应的字符的可能组合就有34=12种(如AP,BR等)。现在
输入一个3到11位长的电话号码,请打印出这个电话号码所对应的字符的所有可能组合和组合数。
*/
package homework;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*电话号码对应的字符组合:在电话或者手机上,一个数字如2对应着字母ABC,7对应着
PQRS。那么数字串27所对应的字符的可能组合就有3*4=12种(如AP,BR等)。现在
输入一个3到11位长的电话号码,请打印出这个电话号码所对应的字符的所有可能组合和组合数。
*/
public class homework3 {
static String[] str= new String[] {"0","1","abc","def",
"ghi","jkl","mno","pqrs","tuv","wxyz"};//定义每个数字对应的字符
public static void main(String[] args) {
System.out.println("请输入3到11位的电话号码:");
Scanner sc=new Scanner(System.in);
String s=sc.next().toString();//将输入的数字转换为字符
String[] s1 = s.split("");//将输入的一串数字分离,并赋给数组s1保存
int sum = sum(s1);
System.out.println("总共有: "+ sum+"种情况");
List<String> answer = letterCombinations( s1,s);
combination(s, 0, answer); //调用组合函数输出所有可能的结果
System.out.println("可能的组合为:"+answer.toString()+"/n");
}
public static int sum(String s1[]) { //计算总共有多少中情况
int len = s1.length;
int sum = 1;
for(int i = 0;i<len; i ++) {
sum *= (str[Integer. valueOf (s1[i])]).length(); //
}
return sum;
}
static StringBuffer sb = new StringBuffer();
public static List<String> letterCombinations(String s1[],String s) {
if (s1.length == 0) {
return null;
}
List<String> answer = new ArrayList<String>();
combination(s , 0 , answer);//开始回溯
return answer;
}
public static void combination(String s1,int n, List<String> answer) {
if (n == s1.length()) {
answer.add(sb.toString());
return;
}
for (int i = 0; i < str[s1.charAt(n)-'0'].length(); i++) {
sb.append(str[s1.charAt(n)-'0'].charAt(i));
combination(s1, n + 1, answer);
sb.deleteCharAt(sb.length() - 1);
}
}
}