leetcode17. Letter Combinations of a Phone Number

python3

class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        if not digits: #这句必不可少,处理空字符串
            return []
        p={}
        p['2'] = ['a','b','c']
        p['3'] = ['d','e','f']
        p['4'] = ['g','h','i']
        p['5'] = ['j','k','l']
        p['6'] = ['m','n','o']
        p['7'] = ['p','q','r','s']
        p['8'] = ['t','u','v']
        p['9'] = ['w','x','y','z']
        res = [i for i in p[digits[0]]]
        for i in digits[1:]:
            res = [m+n for m in res for n in p[i]]
        return res

总结:

觉得比较精妙的几句代码:

-if not x:(当x为真时不执行,x为假时,not x为真,才执行),与之同理的还有,if x is not None:(这种写法最清楚,建议这么写)

  • res = [i for i in p[digits[0]]] 一句话搞定,不需要再创建空列表,写for循环,append值了,虽然意思一样,但是代码简化了不止一点点。
  • res = [m+n for m in res for n in p[i]],这句就更精妙了,两重循环可以这么写,学习了!

猜你喜欢

转载自blog.csdn.net/aaon22357/article/details/83374011
今日推荐