电话号码的字母组合

链接

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
};
相关推荐
happymaker06264 分钟前
简单LRU的实现(基于LinkedHashMap)
算法·leetcode·lru
likerhood7 分钟前
Fastjson中的JSON.parseObject()详细讲解
java·json
KNeeg_9 分钟前
黑马点评完整代码(RabbitMQ优化)+简历编写+面试重点 ⭐
java·redis·后端·spring·面试·职场和发展·黑马点评
「已注销」12 分钟前
面试分享:二本靠7轮面试成功拿下大厂P6
前端·javascript·面试
会编程的土豆16 分钟前
【数据结构与算法】空间复杂度从入门到面试:不仅会算,还要会解释
数据结构·c++·算法·面试·职场和发展
普通网友17 分钟前
《算法面试必刷:15 个高频 LeetCode 题(附代码)》
算法·leetcode·面试
_深海凉_19 分钟前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
张槊哲30 分钟前
C++ 进阶指南:如何丝滑地理解与实践多线程与多进程
开发语言·c++·算法
walking95731 分钟前
重新学习前端之设计模式与架构
前端·javascript·面试
铁皮哥33 分钟前
【后端/Agent 开发】给你的项目配置一套 .claude/ 工作流:别再裸用 Claude Code 了!
java·windows·python·spring·github·maven·生活