给定这本字典:const DIGIT_TO_LETTERS = { 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']}找出按下了什么数字来得到这个词'mad'。我似乎找不到不是 n^2 的解决方案(遍历每个数组并寻找字母)。
1 回答

慕丝7291255
TA贡献1859条经验 获得超6个赞
您可以为字母及其数字获取一个对象,并通过查找某个字母进行转换。
const
DIGIT_TO_LETTERS = { 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'] },
LETTERS_TO_DIGITS = Object
.entries(DIGIT_TO_LETTERS)
.reduce((r, [v, letters]) => {
letters.forEach(l => r[l] = +v);
return r;
}, {}),
convert = string => Array.from(string, l => LETTERS_TO_DIGITS[l]);
console.log(convert('mad'))
添加回答
举报
0/150
提交
取消