500. Keyboard Row
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.
American keyboard
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.
解法
正则匹配
public class Solution {
public String[] findWords(String[] words) {
if (words == null || words.length == 0) {
return words;
}
List<String> list = new ArrayList<>();
String regex = "[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*";
for (String str : words) {
if (str.toLowerCase().matches(regex)) {
list.add(str);
}
}
String[] ret = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
ret[i] = list.get(i);
}
return ret;
}
}