前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode之-题17

leetcode之-题17

作者头像
GavinZhou
发布2018-01-02 15:40:18
5040
发布2018-01-02 15:40:18
举报
文章被收录于专栏:机器学习实践二三事

题目

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 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 题解
    • 思路
      • python代码
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档