持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情
面试题 16.20. T9键盘
在老式手机上,用户通过数字键盘输入,手机将提供与这些数字相匹配的单词列表。每个数字映射到0至4个字母。给定一个数字序列,实现一个算法来返回匹配单词的列表。你会得到一张含有有效单词的列表。映射如下图所示:
「示例1:」
输入: num = "8733", words = ["tree", "used"]
输出: ["tree", "used"]
「示例2:」
输入: num = "2", words = ["a", "b", "c", "d"]
输出: ["a", "b", "c"]
「提示:」
num.length <= 1000
words.length <= 500
words[i].length == num.length
num中不会出现 0, 1 这两个数字
解题思路
// 第一种
创建一个数组,建立数字和字母的映射关系
遍历单词数组,对于当前单词word,再遍历当前单词
判断num相应位置的数字,映射的字母是否包含word相应位置的字母
若包含,放入答案数组
// 第二种
Map过滤
代码实现
// 第一种
const getValidT9Words = (num, words) => {
// 建立数字和字母的映射关系
const num2char = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
const res = [];
// 设置flag,默认为true
let flag = true;
const len = words.length;
for (let i = 0; i < len; i++) {
// 重置flag为true,防止上一个单词为false
flag = true;
// 当前单词
const word = words[i];
for (let j = 0; j < word.length; j++) {
// 遍历当前单词,判断num相应位置的数字,是否包含相应位置的字母
if (!num2char[num[j]].includes(word[j])) {
// 没包含,flag设置为false,直接退出循环
flag = false;
break;
}
}
// 若包含,放入答案数组
flag && res.push(word);
}
return res;
};
// 第二种
/**
* @param {string} num
* @param {string[]} words
* @return {string[]}
*/
const mp = new Map()
mp.set('2', ['a', 'b', 'c'])
mp.set('3', ['d', 'e', 'f'])
mp.set('4', ['g', 'h', 'i'])
mp.set('5', ['j', 'k', 'l'])
mp.set('6', ['m', 'n', 'o'])
mp.set('7', ['p', 'q', 'r', 's'])
mp.set('8', ['t', 'u', 'v'])
mp.set('9', ['w', 'x', 'y', 'z'])
var getValidT9Words = function (num, words) {
let res = words
for (let i = 0; i < num.length; ++i) {
let arr = mp.get(num.charAt(i))
res = res.filter(val => arr.includes(val.charAt(i)))
}
res = res.filter(val => val.length == num.length)
return res
};
如果你对这道题目还有疑问的话,可以在评论区进行留言;