题目描述

大致思路:首先建立数字与字母对应关系
const map = new 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']]
]);
然后遍历参数字符串, 将字符对应的数组push进一个数组, 生成一个二维数组
// '234' => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
const tmp: string[][] = [];
for (let i = 0; i < digits.length; ++i) {
if (map.has(+digits[i])) tmp.push(map.get(+digits[i])!);
}
最后通过 reduce
将 二维数组转化为对应的结果
let res: string[] = [];
//考虑边界情况
if (!digits || Array.from(digits).some((item) => +item < 2)) return res;
//这里也可以用es6的 Array.prototype.flat()来实现数组扁平化
res = tmp.reduce((res, current) => flatArray<string>(res.map((r) => current.map((c) => r + c))));
//数组扁平化
export function flatArray<T>(arr: any[]): T[] {
return arr.reduce((res, current) => Array.isArray(current) ? [...res, ...flatArray(current)] :
[...res, current], []);
}
//测试代码
it('letterCombinations', () => {
expect(letterCombinations('')).toEqual([]);
expect(letterCombinations('1')).toEqual([]);
expect(letterCombinations('123')).toEqual([]);
expect(letterCombinations('23')).toEqual(['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']);
expect(letterCombinations('234')).toEqual([
'adg', 'adh', 'adi', 'aeg',
'aeh', 'aei', 'afg', 'afh',
'afi', 'bdg', 'bdh', 'bdi',
'beg', 'beh', 'bei', 'bfg',
'bfh', 'bfi', 'cdg', 'cdh',
'cdi', 'ceg', 'ceh', 'cei',
'cfg', 'cfh', 'cfi'
]);
});
it('flatArray', () => {
expect(flatArray([[]])).toEqual([]);
expect(flatArray([[1, 2, 3], [4, 5, 6]])).toEqual([1, 2, 3, 4, 5, 6]);
expect(flatArray([[1, 2, 3]])).toEqual([1, 2, 3]);
expect(flatArray([[[1], [2], [3]], [[4], [5], [6]]])).toEqual([1, 2, 3, 4, 5, 6]);
expect(flatArray([[1, [[2]], [3]], [[4], [5], [6]]])).toEqual([1, 2, 3, 4, 5, 6]);
});
提交记录
