LeetCode每日一练【17】

Letter Combinations of a Phone Number

我的解法

第一次提交

介绍

虽然没有什么期待, 但是貌似结果出乎意料的好, 使用三重循环遍历的方式解决问题

思路

  1. 其实没啥好说的, 就一层一层嵌套循环遍历呗

代码

/*
 * @Author: fox
 * @Date: 2022-05-02 17:04:48
 * @LastEditors: fox
 * @LastEditTime: 2022-05-02 18:33:03
 * @Description: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
 */

/**
 * @description: Runtime: 91.73%  Memory Usage: 93.12%
 * @param {string} digits
 * @return {string[]}
 */
const phoneNumber = {
    '0': [],
    '1': [],
    '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']
}

const letterCombinations = (digits, phone = phoneNumber) => {
    let res = []; // 存放结果数组
    let store = []; // 存放三次循环的结果
    let temp = []; // 存放一次循环的结果

    if (!digits || digits.length === 0 ) return []; // 如果digits未定义或者length为0, 直接返回[]

    if (digits.length === 1 && phone[digits[0]].length === 0) return []; // 如果digits.length=1,并且digtis[0]=1 or 0,直接返回[]

    res = phone[digits[0]];

    for (let i = 1; i < digits.length; i++) {
        temp = phone[digits[i]];
        store = [];

        for (const re of res) {
            for (const element of temp) {
                store.push(re+element);
            }
        }

        res = store;
    }

    return res
}

let digits = '23'
console.log(letterCombinations(digits))

digits = ''
console.log(letterCombinations(digits))

digits = '2'
console.log(letterCombinations(digits))

posted @ 2022-05-02 18:42  白い故雪  阅读(12)  评论(0编辑  收藏  举报