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 letterCombinations(String digits) {
        List list = new ArrayList();
        
        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 addList(char c,List 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 al = new ArrayList();
            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;
        }
    }
}



你可能感兴趣的:(leetCode)