首页 > 试题广场 >

电话字母的组合

[编程题]电话字母的组合
  • 热度指数:9364 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给出一个仅包含数字的字符串,给出所有可能的字母组合。
数字到字母的映射方式如下:(就像电话上数字和字母的映射一样)

Input:Digit string "23"Output:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
注意:虽然上述答案是按字典序排列的,但你的答案可以按任意的顺序给出
示例1

输入

"23"

输出

["ad","ae","af","bd","be","bf","cd","ce","cf"]
class Solution:
    def letterCombinations(self , digits ):
        # write code here
        worddict = {'2':'abc','3':'def','4':'ghi','5':'jkl',
                    '6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        digits = list(digits)
        res = ['']
        for digit in digits:
            if digit in worddict:
                word = worddict[digit]
                l = len(word)
                n = len(res)
                #先对res扩容,再按顺序填充
                res = res*l
                for i in range(l):
                    for j in range(n):
                        res[i*n+j] = res[i*n+j] + word[i]
        return sorted(res)

发表于 2020-06-18 16:00:25 回复(0)
# @param digits string字符串 
# @return string字符串一维数组
#
class Solution:
    def letterCombinations(self , digits ):
        # write code here
        sources = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        res = ['']
        
        for i in digits:
            if i in sources:
                ss = sources[i]
            res = [x+y for x in res for y in ss]
        return res
此解法,我借鉴的。但是这种解法的前提是,输入的有效数字不能超过2位,不然解法好像还是有问题。
发表于 2020-06-16 12:05:12 回复(3)

问题信息

难度:
2条回答 13153浏览

热门推荐

通过挑战的用户

查看代码