LeetCode #17 Letter Combinations of a Phone Number

ieunjung·2020년 9월 20일

https://leetcode.com/problems/letter-combinations-of-a-phone-number/

문제파악

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.
2-9 사이의 숫자로 이루어진 번호가 주어진다. 각 숫자에 매핑된 문자에 따라서 출력 가능한 문자열을 모두 구하라.

예제파악

Input: "23"

2, 3의 매핑 문자열은 다음과 같다.
A: ["a", "b", "c"]
B: ["d", "e", "f"]

전화 다이얼의 특성을 생각하면
A, B에서 문자 하나씩 가져올 수 있고, 앞에서 나왔던 문자는 다시 반복될 수 없다.
A, B의 조합을 모두 구하면 Output과 같다.

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

코드

다른 사람의 코드를 참고했다.
먼저 숫자와 문자 매핑을 구해놓고 시작한다. 주의할 점은 7과 9에 해당하는 문자열이 4개씩이라는 것이다.
reduce를 사용해서 이전에 구한 조합 + 새로운 문자를 쉽게 더할 수 있었다.
빈 배열도 들어오기 때문에 예외처리한다.

/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function(digits) {
    if(digits.length === 0 || !digits){
        return [];
    }
    
    const map = {
      "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"]
    };

    let psbLetters = [];

    // 가능한 문자열 구하기
    psbLetters = digits.split("").map(digit => map[digit]);

    // 조합 구하기
    const answer = psbLetters.reduce((acc, psbLetter) => {
        let list = [];
        psbLetter.forEach(letter => {
            list = list.concat(acc.map(a => a + letter));
        });
        return list;
    })

    return answer;
};
profile
Done is better than perfect

0개의 댓글