电话号码的字母组合
算法内容
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = “23”
输出:[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
示例 2:
输入:digits = “”
输出:[]
示例 3:
输入:digits = “2”
输出:[“a”,“b”,“c”]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
算法思想
该算法采用的复杂思想,将每种长度的情况依依列出来,算法思想没有什么可说的。直接看整体算法便可以理解。
整体算法
- 复杂思想
public class Day_16 {
public static String [] s={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
public static List<String> letterCombinations(String digits) {
int length=digits.length();
List<String> list=new ArrayList<String>();
if (length==1){
String one_11=new String();
one_11+=digits.charAt(0);
int one_1=Integer.valueOf(one_11);
System.out.println(one_1+" "+digits.charAt(0));
String one=new String();
for (int i = 0; i < s[one_1-2].length(); i++) {
one+=s[one_1-2].charAt(i);
list.add(one);
one="";
}
}else if(length==2){
int two_1=Integer.valueOf(String.valueOf(digits.charAt(0)));
int two_2=Integer.valueOf(String.valueOf(digits.charAt(1)));
String [] a=mapping(s[two_1-2],s[two_2-2]);
for (int i = 0; i < a.length; i++) {
list.add(a[i]);
}
}else if(length==3){
int three_1=Integer.valueOf(String.valueOf(digits.charAt(0)));
int three_2=Integer.valueOf(String.valueOf(digits.charAt(1)));
int three_3=Integer.valueOf(String.valueOf(digits.charAt(2)));
String three=new String();
String [] a=mapping(s[three_1-2],s[three_2-2]);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < s[three_3-2].length(); j++) {
three+=a[i];
three+=s[three_3-2].charAt(j);
list.add(three);
three="";
}
}
}else if(length==4){
int four_1=Integer.valueOf(String.valueOf(digits.charAt(0)));
int four_2=Integer.valueOf(String.valueOf(digits.charAt(1)));
int four_3=Integer.valueOf(String.valueOf(digits.charAt(2)));
int four_4=Integer.valueOf(String.valueOf(digits.charAt(3)));
String []a=mapping(s[four_1-2],s[four_2-2]);
String []b=mapping(s[four_3-2],s[four_4-2]);
String four=new String();
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
four+=a[i];
four+=b[j];
list.add(four);
four="";
}
}
}
return list;
}
public static String[] mapping(String s,String q){
String [] w=new String[s.length()*q.length()];
int r=0;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < q.length(); j++) {
String p=new String();
p+=s.charAt(i);
p+=q.charAt(j);
w[r]=p;
r++;
}
}
return w;
}
static Scanner input=new Scanner(System.in);
public static void main(String[] args) {
String s=input.nextLine();
List<String> list=letterCombinations(s);
System.out.println(list);
}
}
尾语
以上属于个人见解,有好的想法可以在下方评论写出自己的想法,大家一起进步。该题是力扣上的题,若有侵权,请及时告知。该题链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number