给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

示例:
<pre>输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
</pre>
注意:
- 你可以重复使用键盘上同一字符。
- 你可以假设输入的字符串将只包含字母。
class Solution {
public String[] findWords(String[] words) {
String[] str = new String[]{"QWERTYUIOPqwertyuiop","ASDFGHJKLasdfghjkl","ZXCVBNMzxcvbnm"};
int strLength = str.length;
List list = new ArrayList();
int arrayIndex = -1;
for(String word : words){//拿到每个输入的单词
int length = word.length();
for(int i = 0; i < strLength; i++){//遍历该单词
if(str[i].contains(word.substring(0,1))) {//拿该单词的第一个字母初步判断它在哪一行
int j = 0;
for(; j < length; j++){//遍历该单词的每个字母,不在这一行跳出循环
if(!str[i].contains(word.substring(j,j+1))){
break;
}
}
if(j == length){//该单词在这一行就添加list
arrayIndex++;
list.add(word);
}
}
}
}
int listSize = list.size();
String[] array = new String[listSize];
for(int i = 0; i < listSize; i++){
array[i] =(String) list.get(i);
}
return array;
}
}
网友评论