美文网首页
17. Letter Combinations of a Pho

17. Letter Combinations of a Pho

作者: Chiduru | 来源:发表于2019-03-14 21:36 被阅读0次

    【Description】
    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.

    image

    Example:

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

    【Idea】
    base解法的逻辑性要求不是很高,主要是代码实现的两点trick:

    1. 数字到字符的映射,定义list: ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'] 将数字以下标形式表示;
    2. result = [ori_str+i for i in digit_str[int(temp_num)] for ori_str in result] 实现嵌套循环。

    【Solution】

    class Solution:
        def letterCombinations(self, digits):
            if digits == "":
                return []
            digit_str = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
            result = ['']
            for temp_num in digits:
                result = [ori_str+i for i in digit_str[int(temp_num)] for ori_str in result]
            return result
    
    

    相关文章

      网友评论

          本文标题:17. Letter Combinations of a Pho

          本文链接:https://www.haomeiwen.com/subject/egzcmqtx.html