电话号码的字母组合

链接

17. 电话号码的字母组合 - 力扣(LeetCode)

思路

  1. 首先我们要先得到 "电话号码" 所对应的 返回数组

  2. 根据得到的返回数组,去进行拼接,但是 js 和 c 语言不一样,需要借助 .charCodeAt(0) 来获取到当前的 ASCII 码

  3. 注意屏幕说的是 要 给的 最后长度的 结果,所以我们在遍历到 最后一位的时候,记录下来即可,如果不是就继续递归

代码:

javascript 复制代码
/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function (digits) {
    let res = [], len = digits.length

    function getChar(char) {
        switch (char) {
            case '2': return new Array(3).fill().map((value, index) => String.fromCharCode('a'.charCodeAt(0) + index));
            case '3': return new Array(3).fill().map((value, index) => String.fromCharCode('d'.charCodeAt(0) + index));
            case '4': return new Array(3).fill().map((value, index) => String.fromCharCode('g'.charCodeAt(0) + index));
            case '5': return new Array(3).fill().map((value, index) => String.fromCharCode('j'.charCodeAt(0) + index));
            case '6': return new Array(3).fill().map((value, index) => String.fromCharCode('m'.charCodeAt(0) + index));
            case '7': return new Array(4).fill().map((value, index) => String.fromCharCode('p'.charCodeAt(0) + index));
            case '8': return new Array(3).fill().map((value, index) => String.fromCharCode('t'.charCodeAt(0) + index));
            case '9': return new Array(4).fill().map((value, index) => String.fromCharCode('w'.charCodeAt(0) + index));
        }
    }

    function getRes(pre, index) {
        if (index >= len) return
        else if (index === len - 1) {
            res.push(...getChar(digits[index]).map(value => {
                return pre + value
            }))
        }
        else getChar(digits[index]).forEach(value => {
            getRes(pre + value, index + 1)
        })
    }

    getRes('', 0)

    return res
};
相关推荐
Java面试题总结10 分钟前
GatewayWorker 从零到一完整指南
java
水龙吟啸15 分钟前
华为2026.6.17机考选择题+编程题【速刷敲黑板】
人工智能·深度学习·算法·华为
脉动数据行情22 分钟前
Java OkHttp 完整封装 GC COMEX 美黄金实时盘口定时拉取工具类
java·okhttp·comex 黄金·外盘贵金属
敖行客 Allthinker27 分钟前
IM 融合专题:后端架构师的核心修炼
java·开发语言·数据库
凌波粒27 分钟前
LeetCode--53. 最大子序和(贪心算法)
算法·leetcode·贪心算法
Hesionberger35 分钟前
快速求解完全平方数的最少数量
开发语言·数据结构·python·算法·leetcode·c#
c2385635 分钟前
《序列 DP:C++ 中的“最长”套路与编辑距离》
c++·算法·动态规划
HAPPY酷37 分钟前
【ROS2】16G 内存笔记本跑 ROS2 仿真?VMware 虚拟机“保姆级”配置指南 (R9 7940HX + RTX 4060)
java·linux·ide·windows·pycharm
aqiu11111138 分钟前
【算法日记 19】LeetCode 1. 两数之和:梦开始的地方,哈希表的降维打击
算法·leetcode·职场和发展
我有满天星辰2 小时前
Vue 3 响应式双雄:ref 与 reactive 完全指南
前端·javascript·vue.js