Leetcode17-Letter Combinations of a Phone Number(Python3)

17. Letter Combinations of a Phone Number

Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.

Paste_Image.png

Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

My Solution

class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if digits == "":
            return []
        dict_d = {'1': ' ', '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz', '0': '*'}
        result = list(dict_d[digits[0]])
        for i in range(1, len(digits)):
            result = [x + y for x in result for y in dict_d[digits[i]]]
        return result

Reference (转)

1:
class Solution:
    # @return a list of strings, [s1, s2]
    def letterCombinations(self, digits):
        if '' == digits: return []
        kvmaps = {
            '2': 'abc',
            '3': 'def',
            '4': 'ghi',
            '5': 'jkl',
            '6': 'mno',
            '7': 'pqrs',
            '8': 'tuv',
            '9': 'wxyz'
        }
        return reduce(lambda acc, digit: [x + y for x in acc for y in kvmaps[digit]], digits, [''])
2:
class Solution:
    # @param {string} digits
    # @return {string[]}
    def letterCombinations(self, digits):
        mapping = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', 
                   '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
        if len(digits) == 0:
            return []
        if len(digits) == 1:
            return list(mapping[digits[0]])
        prev = self.letterCombinations(digits[:-1])
        additional = mapping[digits[-1]]
        return [s + c for s in prev for c in additional]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,494评论 0 23
  • 有了孩子,没了工作,生活开销增多了,很多宝妈们都希望利用空余时间再创业,这样既可以减轻家庭负担,又可以拥有一番自己...
    姚飞文案阅读 4,264评论 1 3
  • 作为一个社会人,学会说话是何等地重要。你不会说话,人人都与你为敌;你学会说话,别人会觉得很舒服,人人都会来帮助你。...
    9a5f69ad48dc阅读 1,868评论 0 0
  • 6月22日,看完了《书都不会读,你还想成功》这本书,想要挑战一下100天33本书计划,第一个10天,计划3本书,想...
    楚丹丹阅读 4,014评论 0 1

友情链接更多精彩内容