其他分享
首页 > 其他分享> > leetcode 电话号码的字母组合 列表生成式的表达破解

leetcode 电话号码的字母组合 列表生成式的表达破解

作者:互联网

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
利用列表生成式的表达可轻松破解。

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        m = {
            '2': list('abc'),
            '3': list('def'),
            '4': list('ghi'),
            '5': list('jkl'),
            '6': list('mno'),
            '7': list('pqrs'),
            '8': list('tuv'),
            '9': list('wxyz'),
            }
        if not digits: return []
        ls1 = ['']
        for i in digits:
            ls1 = [x + y for x in ls1 for y in m[i]]
        return ls1

首先生成一组字典。然后剔除空集。然后利用个二维列表来实现即可
在这里插入图片描述

标签:digits,生成式,list,列表,ls1,字母组合,leetcode
来源: https://blog.csdn.net/weixin_41693076/article/details/98238205