首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >leetcode之-题17

leetcode之-题17

作者头像
GavinZhou
发布于 2018-01-02 15:40:18
发布于 2018-01-02 15:40:18
7420
举报

题目

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.

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

题解

思路

1 使用字典存储每个键代表的字母 2 获得输入的数字 3 迭代对输入的数字进行组合

python代码
代码语言:javascript
复制
class Solution(object):
    def combine(self, str1, str2):
        """
        :type str1: list[str]
        :type str2: list[str]
        :rtype: list[str]
        """
        """
        对两个list进行合并,比如['a','b']和['d','e'合并为['ad','ae','bd','be']
        """
        ret = []
        if len(str1) == 0:
            return str2
        if len(str2) == 0:
            return str1
        for x in str1:
            for y in str2:
                ret.append(x+y)
        return ret

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        ret = []
        if len(digits) == 0:
            return ret
        dic = dict({'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'})
        for x in digits:
            str2 = list(dic[x])
            ret = self.combine(ret,str2)
        return ret     
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-02-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 题目
  • 题解
    • 思路
    • python代码
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档