관리 메뉴

솜씨좋은장씨

[leetCode] 17. Letter Combinations of a Phone Number (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 17. Letter Combinations of a Phone Number (Python)

솜씨좋은장씨 2020. 10. 6. 19:08
728x90
반응형

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

 

Example 1:

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

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

 

Constraints:

  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range ['2', '9'].

Solution

from itertools import combinations

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        num2word = {"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']}
        
        if digits == "":
            return []
        else:
            digit_num_list = list(digits)
            
            if len(digit_num_list) == 1:
                return num2word[digit_num_list[0]]
            else:
                word_list = [num2word[digit_num] for digit_num in digit_num_list]
                
                pre_list = word_list[0]
                
                post_lists = word_list[1:]
                
                
                # print("pre_list : {}, post_lists : {}".format(pre_list, post_lists))
                
                for post_list in post_lists:
                    comb_list = self.make_combination_list(pre_list, post_list)
                    
                    pre_list = comb_list
        # print("result : {}".format(comb_list))
                    
        return comb_list
                
                
    @classmethod
    def make_combination_list(self, list1, list2):
        my_comb = []
        
        # print("list1 : {}, list2: {}".format(list1, list2))
        
        
        for word1 in list1:
            for word2 in list2:
                my_comb.append(word1 + word2)
                
        return my_comb

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments