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.
题意:
判断一个单词的每一个字母是否都来自键盘上的同一行,是的话就放在最终结果的数组中
算法思路:
1.首先用3个字符串数组存放三行的字母
2.然后将三行的字母放到map中,对map设置不同的行设置不同的值
3.取每个单词的首字母进行判断,如果在map中取出的值不相等,flag=0,如果都满足在数组集合中添加这个单词
4.将数组list转化为数组
注意:在取每个单词的字母时,取出的是char类型的,直接get键值拿到的是NULL,所以在前面加上“”用来匹配字符串
代码实现
package easy;
import java.util.ArrayList;
import java.util.HashMap;
public class KeyboardRow {
public static String[] findWords(String[] words) {
String[] row1 = {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"};
String[] row2 = {"a", "s", "d", "f", "g", "h", "j", "k", "l"};
String[] row3 = {"z", "x", "c", "v", "b", "n", "m"};
HashMap hashMap = new HashMap();
ArrayList list = new ArrayList();
//添加第一行
for(int i=0; i<row1.length; i++){
hashMap.put(row1[i], 1);
}
//添加第二行
for(int i=0; i<row2.length; i++){
hashMap.put(row2[i], 2);
}
//添加第三行
for(int i=0; i<row3.length; i++){
hashMap.put(row3[i], 3);
}
for(int i=0; i<words.length; i++){//遍历每一个单词
boolean flag = true;
for(int j=0; j<words[i].length(); j++){
if(hashMap.get("" + words[i].toLowerCase().charAt(0)) != hashMap.get("" + words[i].toLowerCase().charAt(j))){
flag = false;
break;
}
}
if (flag){
list.add(words[i]);
}
}
String[] result = new String[list.size()];
return (String[])list.toArray(result);
}
public static void main(String[] args){
String[] words = {"Hello", "Alaska", "Dad", "Peace"};
String[] result = findWords(words);
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
}
}