1. 程式人生 > >leetcode17. Letter Combinations of a Phone Number

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]],這句就更精妙了,兩重迴圈可以這麼寫,學習了!