题目
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"]
解法
public class Solution {
public String[] findWords(String[] words) {
HashMap<Character, Integer> map = new HashMap<>();
ArrayList<String> list = new ArrayList<>();
//字符表加入到map中,每一行用不同index表示
String[] strs = new String[]{"qwertyuiop","asdfghjkl","zxcvbnm"};
for(int i = 0; i < strs.length; i ++){
for(char c : strs[i].toCharArray()){
map.put(c, i);
}
}
//判断单词中每个字符是否和首字符是否在同一行
for(String w : words){
int index = map.get(w.toLowerCase().charAt(0));
for(char c : w.toLowerCase().toCharArray()){
if(map.get(c)!=index){
index = -1;
break;
}
}
if(index != -1)
list.add(w);
}
return list.toArray(new String[0]);
}
}
解法分析:将键盘每一行字符存在map中,用0、1、2来表示行。对每个单词分析,如果有一个单词和首字符不在同一行,则退出循环;否则都可以用同一行表示。
简单解法(不太会):
public String[] findWords(String[] words) {
return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")).toArray(String[]::new);
}
分析:运用了函数式编程和正则表达式