Leetcode17 Letter Combinations of a Phone Number

Question:

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"].

Thinking

迭代思想!想法:‘2345’代表一个字符串,每一个数字又代表着一个字符列表(如 ‘2’ 代表['a','b','c']这个list)
如果只有'2'这一个数字,那么结果当然就是['a','b','c']这个答案。如果想知道‘23’能组合的字符列表,就把['a','b','c']和['c','d','e']两两组合。'234'就把‘23’得到的结果和'4'代表的list组合。这样就永远只用考虑两个列表的组合。

Codes

 class Solution(object):
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        size = len(digits)
        ans = []
        # 从后往前
        for i in range(size - 1, -1, -1):
            l1 = self.GetList(digits[i])
            ans = self.ListsCombinations(l1, ans)
        return ans


    def GetList(self, c):
        ans = []
        if c == '0' or c == '1':
            return ans
        elif c <= '6':
            num = int(c) - 2
            start = ord('a') + num * 3
            for i in range(start, start + 3):
                ans.append(chr(i))
        elif c == '7':
            ans.extend(['p', 'q', 'r', 's'])
        elif c == '8':
            ans.extend(['t', 'u', 'v'])
        elif c == '9':
            ans.extend(['w', 'x', 'y', 'z'])
        return ans



    def ListsCombinations(self, l1, l2):
        size1 = len(l1)
        size2 = len(l2)
        ans = []
        if size1 == 0 or size2 == 0:
            if size1 == 0:
                ans = l2
            else:
                ans = l1
            return ans
        for i in range(size1):
            for j in range(size2):
                ans.append(l1[i] + l2[j])
        return ans

Key Points

# 这是入口
def letterCombinations(self, digits):
# 得到数字字符代表的字符列表 (键盘)
 def GetList(self, c):
 # 组合两个列表
  def ListsCombinations(self, l1, l2):

Performance of Codes:

Pretty Good!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 17. Letter Combinations of a Phone Number Given a digit s...
    LdpcII阅读 1,585评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,877评论 19 139
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 作者:清秋 很小的时候,家人就教导我做人要讲诚信。我总是懵懵懂懂地点点头,说了声:“嗯”,心里却在想诚信到...
    浅香修心阅读 3,655评论 0 5
  • 盼望着,盼望着,曙光已在不远处,然而,自己的身体却极度不给力:颈椎隐隐作痛!孩子们的成绩也不尽如人意,心里...
    唯美儿阅读 2,738评论 0 3

友情链接更多精彩内容