Skip to content

Latest commit

 

History

History
159 lines (104 loc) · 4.22 KB

letter-combinations-of-a-phone-number.md

File metadata and controls

159 lines (104 loc) · 4.22 KB

17. Letter Combinations of a Phone Number - 电话号码的字母组合

Tags - 题目标签

Description - 题目描述

EN:

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 digits 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'].

ZH-CN:

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

 

示例 1:

输入:digits = "23"
输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

示例 2:

输入:digits = ""
输出:[]

示例 3:

输入:digits = "2"
输出:["a","b","c"]

 

提示:

  • 0 <= digits.length <= 4
  • digits[i] 是范围 ['2', '9'] 的一个数字。

Link - 题目链接

LeetCode - LeetCode-CN

Latest Accepted Submissions - 最近一次 AC 的提交

Language Runtime Memory Submission Time
typescript 64 ms 43.8 MB 2022/05/01 23:52
function letterCombinations(digits: string): string[] {
  if (digits === '') {
    return [];
  }

  const map = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];

  const digitsArr = digits.split('');

  return digitsArr.reduce((acc: string[], cur, idx) => {
    const combine = map[parseInt(cur) - 2].split('');

    if (idx === 0) {
      return [...combine];
    }
    
    return acc.reduce((innerAcc, innerCur) => {
      return [...innerAcc, ...combine.map(i => {
        return `${innerCur}${i}`;
      })];
    }, [])
  }, []);


};

My Notes - 我的笔记

reduce 套 reduce 搞定:

function letterCombinations(digits: string): string[] {
  if (digits === '') {
    return [];
  }

  const map = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];

  const digitsArr = digits.split('');

  return digitsArr.reduce((acc: string[], cur, idx) => {
    const combine = map[parseInt(cur) - 2].split('');

    if (idx === 0) {
      return [...combine];
    }
    
    return acc.reduce((innerAcc, innerCur) => {
      return [...innerAcc, ...combine.map(i => {
        return `${innerCur}${i}`;
      })];
    }, [])
  }, []);


};