leetcode-500-Keyboard-Row

描述


Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.

American keyboard

Example 1:

1
2
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

解决方案1(Javascript)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @param {string[]} words
* @return {string[]}
*/
var findWords = function(words) {
var rows = {
"row1": ['q','w','e','r','t','y','u','i','o','p'],
"row2":['a','s','d','f','g','h','j','k','l'],
"row3":['z','x','c','v','b','n','m']
}
var result = []
for (let i = 0; i < words.length; i++) {
var word = words[i].toLowerCase();
if (ifWordOnRow(word, rows["row1"])) {
result.push(words[i]);
}
if (ifWordOnRow(word, rows["row2"])) {
result.push(words[i]);
}
if (ifWordOnRow(word, rows["row3"])) {
result.push(words[i]);
}
}
return result;
};

var ifWordOnRow = (word, row) => {
for (let i = 0; i < word.length; i++) {
if (!row.includes(word[i])) {
return false;
}
}
return true;
}

题目来源