lintcode,电话号码的字母组合

给一个不包含01的数字字符串,每个数字代表一个字母,请返回其所有可能的字母组合。
下图的手机按键图,就表示了每个数字可以代表的字母。
样例
给定 “23”
返回 [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]

一刷ac
解题思路:和全排列的思路相同,这里还是用队列存储可能的字母组合,然后查找数组对应的字母,然后更新字母组合。和全排列都要注意的一个细节是初始化队列之后,加入一个空的对象进去,为了从头遍历。

public class Solution {
    /**
     * @param digits A digital string
     * @return all posible letter combinations
     */
    public ArrayList<String> letterCombinations(String digits) {
        ArrayList<String> res = new ArrayList<String>();
        if(digits == null || digits.length() == 0) return res;
        HashMap<Character, String> map = new HashMap<Character, String>();
        LinkedList<String> queue = new LinkedList<String>();
        queue.add("");
        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");
        for(int i = 0; i < digits.length(); i++){
            String str = map.get(digits.charAt(i));
            int size = queue.size();
            for(; size > 0; size--){
                String s = queue.pollFirst();
                for(int j = 0; j < str.length(); j++){
                    String tmp = s + str.charAt(j);
                    queue.add(tmp);
                }
            }
        }
        res.addAll(queue);
        return res;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值