给出一个仅包含数字的字符串,给出所有可能的字母组合。
数字到字母的映射方式如下:(就像电话上数字和字母的映射一样)
Input:Digit string "23"Output:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].注意:虽然上述答案是按字典序排列的,但你的答案可以按任意的顺序给出
Input:Digit string "23"Output:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].注意:虽然上述答案是按字典序排列的,但你的答案可以按任意的顺序给出
"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)
# @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位,不然解法好像还是有问题。