LeetCode 17. Letter Combinations of a Phone Number

题目:

给定一个包含2-9个数字的字符串,返回该数字可能表示的所有字母组合。下面给出了数字到字母的映射(就像电话按钮一样)。注意,1不映射到任何字母

即:

每个字符(数字)对应一个集合,输入字符串,求其对应的集合相同长度的排列

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Input: "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.
注意:尽管上面的答案是按照字典顺序排列的,但是答案可以是任何顺序

 

思路:

用字典存储数字和字符的一一对应,具体为Integer-String 其中String为字符串,如abc,def

自下而上地进行字符串拼接(如从第一个位置开始遍历则会出现重复遍历)

如对字符串“234”

先将4对应的字符一一添加到结果中,re中有g h i

再将3对应的字符一一与re中已有的字符进行组合:1. d与re组合,得到dg dh di;2. e与re组合,得到eg eh ei;3. d与re组合,得到dg dh di,这九个字符串形成新的re

再将2对应的字符一一与re中已有的字符进行组合,具体有点多就不打出来啦

遍历完之后返回re

【注意】最开始想的是1是否在字符串中表示为1,还有0在字符串中是否表示为0,测试之后发现需要的是将1和0都忽略,所以代码中直接跳过1和0的处理

 

更快的方法:

https://segmentfault.com/a/1190000003766442

 

自己的代码:

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> re = new LinkedList<String>();     
        HashMap<Integer, String> dict = getDict();

        
        for(int i=digits.length()-1;i>=0;i--) {
            // 最开始时 re为空,先添加“”,使后续算法可直接添加字符
            if(i==digits.length()-1){
                re.add("");
            }

            int s = digits.charAt(i)-'0';
            // 跳过0和1的处理
            if(s!=0 && s!=1) {
                re = combine(re,s,dict.get(s));
            }
        }
        return re;
    }
    
    public List<String> combine(List<String> re, int s,String dictS){
        List<String> newRe = new LinkedList<String>();
    	
        for(int i=0;i<dictS.length();i++) {
            char locI = dictS.charAt(i);
            for(String tempS:re) {
                newRe.add(locI+tempS);
            }
        }
        return newRe;
    }
    
    
    public HashMap<Integer, String> getDict(){
        HashMap<Integer, String> dict = new HashMap<Integer, String>();
        dict.put(2, "abc");
        dict.put(3, "def");
        dict.put(4, "ghi");
        dict.put(5, "jkl");
        dict.put(6, "mno");
        dict.put(7, "pqrs");
        dict.put(8, "tuv");
        dict.put(9, "wxyz");
    	   
        return dict;	
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值