题目描述
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
示例:
输入: [“Hello”, “Alaska”, “Dad”, “Peace”]
输出: [“Alaska”, “Dad”]
注意:
你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。
代码
public class Solution {
public String[] findWords(String[] words){
String[] res;
if(words.length == 0){
res = new String[0];
return res;
}
List<String> resList = new ArrayList<>();
List<Character> first = new ArrayList<>();
first.add('Q');
first.add('q');
first.add('W');
first.add('w');
first.add('E');
first.add('e');
first.add('R');
first.add('r');
first.add('T');
first.add('t');
first.add('Y');
first.add('y');
first.add('U');
first.add('u');
first.add('I');
first.add('i');
first.add('O');
first.add('o');
first.add('P');
first.add('p');
List<Character> second = new ArrayList<>();
second.add('A');
second.add('a');
second.add('S');
second.add('s');
second.add('D');
second.add('d');
second.add('F');
second.add('f');
second.add('G');
second.add('g');
second.add('H');
second.add('h');
second.add('J');
second.add('j');
second.add('K');
second.add('k');
second.add('L');
second.add('l');
List<Character> third = new ArrayList<>();
third.add('Z');
third.add('z');
third.add('X');
third.add('x');
third.add('C');
third.add('c');
third.add('V');
third.add('v');
third.add('B');
third.add('b');
third.add('N');
third.add('n');
third.add('M');
third.add('m');
for(int i=0;i<words.length;i++){
//若当前单词由一个字母构成
if(words[i].length() == 1){
resList.add(words[i]);
continue;
}
char sample = words[i].charAt(0);
if(first.contains(sample)){
for(int j=1;j<words[i].length();j++){
if(!first.contains(words[i].charAt(j))){
break;
}
//比对成功,加入结果集
if(j==words[i].length()-1){
resList.add(words[i]);
}
}
}else if(second.contains(sample)){
for(int j=1;j<words[i].length();j++){
if(!second.contains(words[i].charAt(j))){
break;
}
//比对成功,加入结果集
if(j==words[i].length()-1){
resList.add(words[i]);
}
}
}else{
for(int j=1;j<words[i].length();j++){
if(!third.contains(words[i].charAt(j))){
break;
}
//比对成功,加入结果集
if(j==words[i].length()-1){
resList.add(words[i]);
}
}
}
}
//将resList中的字符串转为数组
res = new String[resList.size()];
for(int i=0;i<resList.size();i++){
res[i] = resList.get(i);
}
return res;
}
}
思考
算法思想比较常规,代码重复的部分比较多,但值得注意的是对各种特殊用例的处理。
性能表现