500. Keyboard Row
2026/1/12大约 2 分钟约 504 字
500. Keyboard Row
难度: Easy
题目描述
Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
Note that the strings are case-insensitive, both lowercased and uppercased of the same letter are treated as if they are at the same row.
In the American keyboard:
- the first row consists of the characters
"qwertyuiop", - the second row consists of the characters
"asdfghjkl", and - the third row consists of the characters
"zxcvbnm".

Example 1:
Input: words = ["Hello","Alaska","Dad","Peace"]
Output: ["Alaska","Dad"]
Explanation:
Both "a" and "A" are in the 2nd row of the American keyboard due to case insensitivity.
Example 2:
Input: words = ["omk"]
Output: []
Example 3:
Input: words = ["adsdf","sfd"]
Output: ["adsdf","sfd"]
Constraints:
1 <= words.length <= 201 <= words[i].length <= 100words[i]consists of English letters (both lowercase and uppercase).
解题思路
代码实现
解决方案
java
class Solution {
public String[] findWords(String[] words) {
List<String> res = new ArrayList<>();
String str1 = "qwertyuiop";
String str2 = "asdfghjkl";
String str3 = "zxcvbnm";
Map<Character, Integer> categoryMap = new HashMap<>();
for (int i = 0; i < str1.length(); i++) {
categoryMap.put(str1.charAt(i), 1);
}
for (int i = 0; i < str2.length(); i++) {
categoryMap.put(str2.charAt(i), 2);
}
for (int i = 0; i < str3.length(); i++) {
categoryMap.put(str3.charAt(i), 3);
}
for (int i = 0; i < words.length; i++) {
if (check(words[i], categoryMap)) {
res.add(words[i]);
}
}
return res.toArray(new String[0]);
}
private boolean check(String str, Map<Character, Integer> categoryMap) {
Integer category = null;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
c = Character.toLowerCase(c);
if (category == null) {
Integer temp = categoryMap.get(c);
if (temp == null) {
return false;
}
category = temp;
continue;
}
if (!category.equals(categoryMap.get(c))) {
return false;
}
}
return true;
}
}