给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。
美式键盘 中:
第一行由字符 "qwertyuiop" 组成。
第二行由字符 "asdfghjkl" 组成。
第三行由字符 "zxcvbnm" 组成。
示例 1:
输入:words = ["Hello","Alaska","Dad","Peace"]
输出:["Alaska","Dad"]
示例 2:
输入:words = ["omk"]
输出:[]
示例 3:
输入:words = ["adsdf","sfd"]
输出:["adsdf","sfd"]
提示:
1 <= words.length <= 20
1 <= words[i].length <= 100
words[i] 由英文字母(小写和大写字母)组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/keyboard-row
class Solution {
public String[] findWords(String[] words) {
String[] str ={"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
int count;
int index;
String test;
List<String> new_words = new LinkedList();//定义一个 String 类型链表,存储属于同一行的输入
for (String word : words) {
count=0; // 记录符合长度的元素个数
test =String.valueOf(word.toUpperCase().charAt(0)) ;
if(str[0].contains(test)) // 根据首字母判断是属于哪一行
{
index=0;
}
else if(str[1].contains(test))
{
index=1;
}
else{
index=2;
}
for (char c : word.toUpperCase().toCharArray()) {
if(str[index].contains(String.valueOf(c)))
{
count+=1;
}
else
break; // 若出现不属于同一行的字母则结束循环
}
if(count==word.length()) // 根据统计的符合的元素个数判断是否都在一行
new_words.add(word);
}
return new_words.toArray(new String[0]); // 将泛型列表转换为字符串数组
}
}