给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
- 第一行由字符
"qwertyuiop"组成。 - 第二行由字符
"asdfghjkl"组成。 - 第三行由字符
"zxcvbnm"组成。
示例 1:
输入: words = ["Hello","Alaska","Dad","Peace"]
输出: ["Alaska","Dad"]
示例 2:
输入: words = ["omk"]
输出: []
示例 3:
输入: words = ["adsdf","sfd"]
输出: ["adsdf","sfd"]
提示:
1 <= words.length <= 201 <= words[i].length <= 100words[i]由英文字母(小写和大写字母)组成
哈希表
//哈希表
function findWords(words: string[]): string[] {
const firstRow = new Set(["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]),
secondRow = new Set(["a", "s", "d", "f", "g", "h", "j", "k", "l"]),
thirdRow = new Set(["z", "x", "c", "v", "b", "n", "m"]);
//过滤不符合的
return words.filter((item) => {
const firstChar = item[0].toLowerCase();
for (const line of [firstRow, secondRow, thirdRow]) {
//如果首字母满足了其中一行,则检查所有字母
if (line.has(firstChar)) {
return [...item].every((s) => line.has(s.toLowerCase()));
}
}
});
}
哈希表2
//哈希表2
function findWords2(words: string[]): string[] {
const firstRow = new Set(["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]),
secondRow = new Set(["a", "s", "d", "f", "g", "h", "j", "k", "l"]),
thirdRow = new Set(["z", "x", "c", "v", "b", "n", "m"]);
//过滤不符合的
return words.filter((item) => {
const firstChar = item[0].toLowerCase();
for (const line of [firstRow, secondRow, thirdRow]) {
//如果首字母满足了其中一行,则检查所有字母
if (!line.has(firstChar)) continue;
for (const s of item) {
if (!line.has(s.toLowerCase())) {
return false;
}
}
return true;
}
});
}