zoukankan      html  css  js  c++  java
  • [LeetCode] 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"].

    思路:假如字符串长度已知,直接采用多重循环效率更高一些。不过这道题长度未知,使用递归,一层一层地递归下去,这种思路很重要,最后需要注意得是检查特殊情况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));
            }
        }
  • 相关阅读:
    java基础学习——编辑器的使用(一)
    nginx配置文件重写url不带index.php
    解决Too many open files问题
    内存溢出
    NetworkInterface获取主机ip,判断内外网
    克隆
    StringUtil
    Model与Record转换适配
    字符串操作工具类
    利用反射机制动态的调用类信息
  • 原文地址:https://www.cnblogs.com/maydow/p/4667687.html
Copyright © 2011-2022 走看看