题目链接
思路
- 首先用一个数组记录每个号码对应的字母数组
- 这里的逻辑是用数组来代替字典,以下标为键,偏移量为 2
- 新建一个空的结果数组
- 遍历数字字符串
- 如果结果数组为空,将对应的字母数组直接 push 到结果数组中
- 如果结果数组不为空,遍历结果数组中的每一项,将它们依次加上字母数组中的每一项后 push 到数组中
- 做完这些后,用一个坐标 cur 记录已经做过「加」处理的元素数量,下次操作从 cur 位置之后的元素开始执行
- 截取 cur 位置开始的元素到末尾,得到最终的结果
var letterCombinations = function (digits) {
const m = [
["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"],
["j", "k", "l"],
["m", "n", "o"],
["p", "q", "r", "s"],
["t", "u", "v"],
["w", "x", "y", "z"],
];
const res = [];
let cur = 0;
for (const d of digits) {
if (!res.length) res.push(...m[parseInt(d) - 2]);
else {
const len = res.length;
for (let i = cur; i < len; i++)
res.push(...m[parseInt(d) - 2].map((e) => res[i] + e));
cur = len;
}
}
res.splice(0, cur);
return res;
};