码迷,mamicode.com
首页 > 其他好文 > 详细

24.Letter Combinations of a Phone Number(电话号对应的字符组合)

时间:2019-04-21 12:59:42      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:image   delete   结果   example   ima   amp   pre   http   character   

Level:

??Medium

题目描述:

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.

技术图片

Example:

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.

思路分析:

??建立hashmap将每个数字对应的字符映射存放在map中,利用递归回溯解决问题。

代码:

public class Solution{
    public List<String>letterCombinations(String digits){
        List<String>res=new ArrayList<>();
        if(digits==null||digits.equals(""))
            return res;
        HashMap<Character,char[]>map=new HashMap<>();
        map.put('0',new char[]{});
        map.put('1',new char[]{});
        map.put('2',new char[]{'a','b','c'});
        map.put('3',new char[]{'d','e','f'});
        map.put('4',new char[]{'g','h','i'});
        map.put('5',new char[]{'j','k','l'});
        map.put('6',new char[]{'m','n','o'});
        map.put('7',new char[]{'p','q','r','s'});
        map.put('8',new char[]{'t','u','v'});
        map.put('9',new char[]{'w','x','y','z'});
        StringBuilder str=new StringBuilder();
        findComb(digits,map,res,str);
        return res;
    }
    public void findComb(String digits,HashMap<Character,char[]>map,List<String>res,StringBuilder str){
        if(str.length==digits.length){//str的长度等于digits的长度证明是其中一个结果
            res.add(str.toString());
            return;
        }
        for(char c:map.get(digits.charAt(str.length()))){
            str.append(c);
            findComb(digits,map,res,str);//递归回溯找出所有的结果
            str.deleteCharAt(str.length()-1);//每找出一个结果后,str的长度减一,添加下一种可能
        }
    }
}

24.Letter Combinations of a Phone Number(电话号对应的字符组合)

标签:image   delete   结果   example   ima   amp   pre   http   character   

原文地址:https://www.cnblogs.com/yjxyy/p/10744615.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!