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:
Input: [“Hello”, “Alaska”, “Dad”, “Peace”] Output: [“Alaska”, “Dad”]
Note: You may use one character in the keyboard more than once. You
may assume the input string will only contain letters of alphabet.
public class Solution {
String[] keyboards = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
public String[] findWords(String[] words) {
int[] result = new int[words.length];
int n = 0;
for (int j = 0; j < words.length; j++) {
String wor = words[j].toLowerCase();
int line = -1;
for (int i = 0; i < keyboards.length; i++) {
String one = wor.substring(0, 1);
if (keyboards[i].contains(one)) {
line = i;
}
}
boolean flag = true;
for (int i = 0; i < wor.length(); i++) {
if (!keyboards[line].contains(wor.substring(i, i + 1))) {
flag = false;
break;
}
}
if (flag == true) {
result[n] = j;
n++;
}
}
String[] results = new String[n];
for (int i = 0; i < n ; i++) {
results[i] = words[result[i]];
}
return results;
}
}
本文介绍了一个LeetCode上的编程题目——键盘行单词。该题要求从输入的字符串数组中筛选出仅使用美国键盘同一行字母组成的单词。通过一个Java实现的解决方案,详细展示了如何检查每个单词是否符合要求,并返回符合条件的所有单词。


被折叠的 条评论
为什么被折叠?



