cool and pythonic solution to leetcode 17.

矫情吗;* 2022-07-15 02:54 208阅读 0赞
  1. Letter Combinations of a Phone Number

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.

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

思路:hashtable+笛卡尔积

my code:

  1. class Solution(object):
  2. def letterCombinations(self, digits):
  3. """
  4. :type digits: str
  5. :rtype: List[str]
  6. """
  7. if not digits:
  8. return []
  9. dict = {'2':['a','b','c'],
  10. '3':['d','e','f'],
  11. '4':['g','h','i'],
  12. '5':['j','k','l'],
  13. '6':['m','n','o'],
  14. '7':['p','q','r','s'],
  15. '8':['t','u','v'],
  16. '9':['w','x','y','z'],
  17. '1':['*'],
  18. '0':[' ']
  19. }
  20. ll = [dict[key] for key in digits]
  21. return [''.join(item) for item in itertools.product(*ll)]

发表评论

表情:
评论列表 (有 0 条评论,208人围观)

还没有评论,来说两句吧...

相关阅读