500.Keyboard Row
Description:
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:
1. You may use one character in the keyboard more than once.
2. You may assume the input string will only contain letters of alphabet.
思路:正则表达式。为了方便,把单词中的字母都转为小写。
代码:
public class Solution {
public String[] findWords(String[] words) {
ArrayList<String> newWords=new ArrayList<String>();
for(String word:words){
if(word.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")){
newWords.add(word);
}
}
return newWords.toArray(new String[newWords.size()]);
}
}
完成。