电话号码的字母组合

来源:互联网 发布:搜狐快站绑定独立域名 编辑:程序博客网 时间:2024/04/30 14:44

Given a digit string excluded 01, 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.

Cellphone

 注意事项

以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。

样例

给定 "23"

返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

代码如下
public class Solution {
    /*
     * @param digits: A digital string
     * @return: all posible letter combinations
     */
    public List<String> letterCombinations(String digits) {
        // write your code here
        return getCombinations(digits,new String(""),new ArrayList<String>());
    }
    public List<String> getCombinations(String digits,String combinations,List<String> coms)
    {
        System.out.println(digits.length());
        if(digits.length()>0)
        {
            String letters=getDigits(digits.charAt(0));
            for(int i=0;i<letters.length();i++)
            {
                String temp=combinations+new Character(letters.charAt(i)).toString();
                getCombinations(digits.substring(1,digits.length()),temp,coms);
            }
        }else {
            if(combinations.length()>0){
           coms.add(combinations);}
        }
        return coms;
    }
    public String getDigits(char a)
    {
        if(a=='1')
        {
            return "";
        }else if(a=='2')
        {
            return "abc";
        }
        else if(a=='3')
        {
            return "def";
        }else if(a == '4')
        {
            return "ghi";
        }else if(a =='5')
        {
            return "jkl";
        }else if(a== '6')
        {
            return "mno";
        }else if(a== '7')
        {
            return "pqrs";
        }else if(a== '8')
        {
            return "tuv";
        }else if(a== '9')
        {
            return "wxyz";
        }
        else if(a== '0')
        {
            return "";
        }
        return "";
    }
}
原创粉丝点击