首页 > 其他 > 详细

[LeetCode] Letter Combinations of a Phone Number

时间:2015-07-22 17:59:09      阅读:172      评论:0      收藏:0      [点我收藏+]

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"].

思路:假如字符串长度已知,直接采用多重循环效率更高一些。不过这道题长度未知,使用递归,一层一层地递归下去,这种思路很重要,最后需要注意得是检查特殊情况null和""。
    public List<String> letterCombinations(String digits) {
        List<String> list=new ArrayList<String>();
        if(digits==null || digits.length()==0)
            return list;
        digits=digits.replace("1","");
        Map<Character, String> map=new HashMap<Character,String>();
        map.put(‘1‘, "");
        map.put(‘2‘, "abc");
        map.put(‘3‘, "def");
        map.put(‘4‘, "ghi");
        map.put(‘5‘, "jkl");
        map.put(‘6‘, "mno");
        map.put(‘7‘, "pqrs");
        map.put(‘8‘, "tuv");
        map.put(‘9‘, "wxyz");
        map.put(‘0‘, " ");
        
        recurseStr(map , digits , 0 , list , "");
        return list;
    }
    private void recurseStr(Map<Character,String> map,String digits,int depth,List<String> list,String re)
    {
        if(depth==digits.length())
        {
            list.add(re);
            return;
        }
        String temp=map.get(digits.charAt(depth));
        for(int i=0;i<temp.length();i++)
        {
            recurseStr(map,digits,depth+1, list, re+temp.charAt(i));
        }
    }

 

[LeetCode] Letter Combinations of a Phone Number

原文:http://www.cnblogs.com/maydow/p/4667687.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!