LeetCode第17题 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例 1: 

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2:

输入:digits = ""
输出:[]

示例 3:

输入:digits = "2"
输出:["a","b","c"]

提示:

0 <= digits.length <= 4
digits[i] 是范围 ['2', '9'] 的一个数字。

 解题思路

1、先将题目所示的键盘放入一张HashMap中

maps.put('2', "abc");
maps.put('3', "def");
maps.put('4', "ghi");
maps.put('5', "jkl");
maps.put('6', "mno");
maps.put('7', "pqrs");
maps.put('8', "tuv");
maps.put('9', "wxyz");

 2、准备一个列表strings存放上一步所有的可能性。

 3、当前字符组合的可能性等于上一部所有的可能性 * 当前步骤所有的可能性。

 

Java代码:

class Solution {
    public List<String> letterCombinations(String digits) {
        HashMap<Character, String> maps = new HashMap<>();
        maps.put('2', "abc");
        maps.put('3', "def");
        maps.put('4', "ghi");
        maps.put('5', "jkl");
        maps.put('6', "mno");
        maps.put('7', "pqrs");
        maps.put('8', "tuv");
        maps.put('9', "wxyz");

        List<String> strings = new ArrayList<>();
        List<String> temp = new ArrayList<>();
        for(int i=0; i<digits.length(); i++){
            if(i==0){
                char c = digits.charAt(i);
                for(char cur:maps.get(c).toCharArray()){
                    temp.add(String.valueOf(cur));
                }
            }else{
                char c = digits.charAt(i);
                for(String string:strings){
                    for(char cur:maps.get(c).toCharArray()){
                        temp.add(string + String.valueOf(cur));
                    }
                }
            }
            strings.clear();
            strings.addAll(temp);
            temp.clear();
        }

        return strings;
    }
}

 Python代码

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        maps = {}
        maps['2'] = 'abc'
        maps['3'] = 'def'
        maps['4'] = 'ghi'
        maps['5'] = 'jkl'
        maps['6'] = 'mno'
        maps['7'] = 'pqrs'
        maps['8'] = 'tuv'
        maps['9'] = 'wxyz'

        strings = []
        temp = []
        for i in range(len(digits)):
            if i == 0:
                c = digits[i]
                for cur in maps[c]:
                    temp.append(cur)
            else:
                c = digits[i]
                for string in strings:
                    for cur in maps[c]:
                        temp.append(string + cur)
            strings = temp[:]
            temp = []
        return strings

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值