原题
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.
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.
解析
输入一组字符串,返回所有能在键盘同一行进行输入的字符串
思路
已知键盘的三行字母,用来匹配每个字符串,返回能够全部匹配的字符串
我的解法
//三行键盘字母
private static String row1 = "qwertyuiop";
private static String row2 = "asdfghjkl";
private static String row3 = "zxcvbnm";
//主方法
public static String[] findWords(String[] words) {
List<String> output = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
char[] chars = words[i].toLowerCase().toCharArray();
if (row1.contains(String.valueOf(chars[0])) && testRow(row1, chars)) {
output.add(words[i]);
continue;
}
if (row2.contains(String.valueOf(chars[0])) && testRow(row2, chars)) {
output.add(words[i]);
continue;
}
if (row3.contains(String.valueOf(chars[0])) && testRow(row3, chars)) {
output.add(words[i]);
continue;
}
}
String[] outputArray = new String[output.size()];
return output.toArray(outputArray);
}
//测试该字符串的每一个字符是否在同一行
private static Boolean testRow(String testString, char[] chars) {
boolean isAdd = true;
for (int j = 1; j < chars.length; j++) {
if (!testString.contains(String.valueOf(chars[j]))) {
isAdd = false;
break;
}
}
return isAdd;
}
最优解法
leetcode上面有人写了一行的最优解。。。。五体投地。。
运用了java8的Stream,和正则表达式,直接匹配一串字符,而不是一个一个匹配
public static String[] findWordsOptimize(String[] words) {
return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]+|[asdfghjkl]+|[zxcvbnm]+")).toArray(String[]::new);
}