leetCode 17.Letter Combinations of a Phone Number(电话数字对应的字母组合) 解题思路和方法

Letter Combinations of a Phone Number


Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.


Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.


思路:算法上很简单,就是将每个数字对应的字符循环相加即可,一次一次的遍历穷举即可。

详细代码和注释如下:

public class Solution {
    //保存为静态变量,效率更高
    public static String[] map = new String[128];  
    
    public List<String> letterCombinations(String digits) {
        List<String> list = new ArrayList<String>();
        
        char[] ch = digits.toCharArray();
        if(ch.length == 0)
            return list;
            
        //按ACSII码保存
        map['0'] = "";  
        map['1'] = "";  
        map['2'] = "abc";  
        map['3'] = "def";  
        map['4'] = "ghi";  
        map['5'] = "jkl";  
        map['6'] = "mno";  
        map['7'] = "pqrs";  
        map['8'] = "tuv";  
        map['9'] = "wxyz"; 

        for(int i = 0; i < ch.length; i++){
            list = addList(ch[i],list);
        }
        return list;
    }
    //将每个数字对应的字符与list相加后返回
    public static List<String> addList(char c,List<String> list){

        String  s = map[c];//读取对应字符串
        if(list.size() == 0){//如果是第一个字符串
            for(int i = 0; i < s.length();i++){
                list.add(s.charAt(i) + "");
            }
            return list;
        }
        else{//不是则循环相加
            List<String> al = new ArrayList<String>();
            for(int i = 0; i < s.length();i++){
                for(int j = 0; j < list.size(); j++){
                    al.add(list.get(j) + s.charAt(i));
                }
            }
            return al;
        }
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值