LeetCode 17. Letter Combinations of a Phone Number(电话号码的字母组合)

原题

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

题目:给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

这里写图片描述

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

Example:

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

Reference solution

分析:题目分析:电话按键想必我们小伙伴再熟悉不过了吧。手机九宫格打起字来一个个溜的飞起!这个题目首先输入是一个数字字符串,每一个数字可以对应几个字母字符。所以首先可以考虑建立一个字典,以键值对的形式存放数据。之后逐位进行数字字符的处理(即对应字母组合拼接)。思路概括如下:

  1. 建立数字字符串和字母的对应关系,以键值对形式存在字典中
  2. 对数字字符串digits逐位处理进行匹配,这里对第 j 位进行处理的时候可以将j-1 位处理的结果拼接第 j 位对应的字符即可
  3. 注意拼接得到的输出形式为列表形式。
class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if not digits: return [] # 数字字符为空时
        #建立一个字典,键值对形式存放电话按键上数字字符对应关系
        table = {'2': ['a', 'b', 'c'],
                '3': ['d', 'e', 'f'],
                '4': ['g', 'h', 'i'],
                '5': ['j', 'k', 'l'],
                '6': ['m', 'n', 'o'],
                '7': ['p', 'q', 'r', 's'],
                '8': ['t', 'u', 'v'],
                '9': ['w', 'x', 'y', 'z']}

        result = [''] # 建立空列表,用于存放结果
        for digit in digits: # 从输入digits中依次对每个数字字符处理
            str_list = [] # 设定一个中间过程存放列表
            for char in table[digit]: # result为存放处理过的前边数字字符
                #这里将新数字对应的字符拼接到前边已有的result中
                str_list += [x + char for x in result] 
            result = str_list #将处理好的前边数字结果存放于result,并继续处理后位
        return result

反思:

  1. python在对list等赋值时候,切忌使用连等式,如a = b = [],list与字符不一样,list这种赋值方式,只是将相同空间list的指针赋值给了a与b,对a修改的同时也对b做出了修改,违背了自身本意,对字符型则没影响。
  2. 自身确实没有考虑到这种“对数字字符串digits逐位处理进行匹配,这里对第 j 位进行处理的时候可以将j-1 位处理的结果拼接第 j 位对应的字符即可”。
  3. 此外,注意:result = [”]而不是[],因为用到了 str_list += [x + char for x in result] ,因为里面用到了字符串的‘+’功能,所以result内部必须加上字符串标识符。

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/82625983