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.
Subscribe to see which companies asked this question.
链接:点击打开链接
先来一种比较好理解的解法,,就是代码多了点,加到Set里面分别比较就可以了,更简单点用HashSet,三行字母作为key,value分别为1,2,3判断value是否相同就好
public static String[] findWords(String[] words) {
HashSet set1=new HashSet();
HashSet set2=new HashSet();
HashSet set3=new HashSet();
List list=new ArrayList();
String a="qwertyuiop";
String b="asdfghjkl";
String c="zxcvbnm";
String[] word=new String[words.length];
for(int i=0;i<a.length();i++){
set1.add(a.charAt(i));
}
for(int i=0;i<b.length();i++){
set2.add(b.charAt(i));
}
for(int i=0;i<c.length();i++){
set3.add(c.charAt(i));
}
//System.out.println(set3);
for(int i=0;i<words.length;i++){
word[i]=words[i];
words[i]=words[i].toLowerCase();
if(set1.contains(words[i].charAt(0))){
int index=1;
for(int j=0;j<words[i].length();j++){
if(!set1.contains(words[i].charAt(j))){
index=0;
break;
}
}
if(index==1){
list.add(word[i]);
}
}
if(set2.contains(words[i].charAt(0))){
int index=1;
for(int j=0;j<words[i].length();j++){
if(!set2.contains(words[i].charAt(j))){
index=0;
break;
}
}
if(index==1){
list.add(word[i]);
}
}
if(set3.contains(words[i].charAt(0))){
int index=1;
for(int j=0;j<words[i].length();j++){
if(!set3.contains(words[i].charAt(j))){
index=0;
break;
}
}
if(index==1){
list.add(word[i]);
}
}
}
//System.out.println(set4);
return (String[]) list.toArray(new String [list.size()]);
}
看到一个大神的解法,膜拜,妙!
public class Solution {
public String[] findWords(String[] words) {
List<String> list = new ArrayList<>();
int[] hash = new int[26];
String[] rows = {"qwertyuiop","asdfghjkl","zxcvbnm"};
for (int i=0; i<rows.length; i++) {
for (char c : rows[i].toCharArray())
hash[c-'a'] += i;
}
for (String word : words) {
char first = Character.toLowerCase(word.charAt(0));
for (int i=1; i<=word.length(); i++) {
if (i == word.length()) {
list.add(word);
break;
}
char c = Character.toLowerCase(word.charAt(i));
if( hash[c-'a'] != hash[first-'a'])
break;
}
}
return list.toArray(new String[0]);
}
}