键盘行

给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
第一行由字符 “qwertyuiop“ 组成。
第二行由字符 “asdfghjkl“ 组成。
第三行由字符 “zxcvbnm“ 组成。

  • 输入:words = [“Hello”,”Alaska”,”Dad”,”Peace”]
  • 输出:[“Alaska”,”Dad”]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 我们为每一个英文字母标记其对应键盘上的行号,然后检测字符串中所有字符对应的行号是否相同。
// 我们可以预处理计算出每个字符对应的行号。
// 遍历字符串时,统一将大写字母转化为小写字母方便计算。

let findWords = function(words) {
const list = [];
const rowIdx = "12210111011122000010020202";
for (const word of words) {
let isValid = true;
const idx = rowIdx[word[0].toLowerCase().charCodeAt() - 'a'.charCodeAt()];
for (let i = 1; i < word.length; ++i) {
if (rowIdx[word[i].toLowerCase().charCodeAt() - 'a'.charCodeAt()] !== idx) {
isValid = false;
break;
}
}
if (isValid) {
list.push(word);
}
}
return list;

};