Java/500. Keyboard Row 键盘行
题目
代码部分一(2ms 99.4%)
class Solution {
List<String> list = new ArrayList();
public String[] findWords(String[] words) {
String frist = "QWERTYUIOPqwertyuiop";
String second = "ASDFGHJKLasdfghjkl";
String third = "ZXCVBNMzxcvbnm";
for(String temp : words){ //遍历String[]
if(frist.indexOf(temp.charAt(0)) != -1)
isNeed(frist, temp);
else if(second.indexOf(temp.charAt(0)) != -1)
isNeed(second, temp);
else if(third.indexOf(temp.charAt(0)) != -1)
isNeed(third, temp);
}
String[] res = list.toArray(new String[list.size()]);
return res;
}
public void isNeed(String str, String temp){ //判断该单词是否符合
int len = temp.length();
for(int i = 0; i < len; i++){
if(str.indexOf(temp.charAt(i)) == -1)
break;
if(i + 1 == len)
list.add(temp);
}
}
}
-
将键盘各行字符存入“frist、second、third”
-
遍历字符数组 words[],判断单词是否符合条件
-
list转换为String[] ,返回结果
代码部分二(1ms 100%)
class Solution {
private static byte[] keyBoard = new byte[]{
1,2,2,1,0,1,1,1,0,1,1,1,2,2,0,0,0,0,1,0,0,2,0,2,0,2,
4,4,4,4,4,4,
1,2,2,1,0,1,1,1,0,1,1,1,2,2,0,0,0,0,1,0,0,2,0,2,0,2
};
public String[] findWords(String[] words) {
List<String> result = new ArrayList<>();
int tmp;
boolean flag;
for(String word : words) {
tmp = keyBoard[word.charAt(0) - 'A'];
flag = true;
for(char c:word.toCharArray()) {
if(tmp != keyBoard[c - 'A']) {
flag = false;
break;
}
}
if(flag) {
result.add(word);
}
}
return result.toArray(new String[result.size()]);
}
}