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.
public class Solution {
public String[] findWords(String[] words) {
ArrayList<String> res = new ArrayList<String>();
String row0="QqWwEeRrTtYyUuIiOoPp";
String row1="AaSsDdFfGgHhJjKkLl";
String row2="ZzXxCcVvBbNnMm";
boolean[] whichr={false,false,false};
int count;
for(int i=0; i<words.length;i++){
count=0;
for(int z=0;z< whichr.length;z++){
whichr[z]=false;
}
for(int j=0;j<words[i].length();j++){
if(row0.indexOf(words[i].substring(j,j+1)) != -1) whichr[0]=true;
if(row1.indexOf(words[i].substring(j,j+1)) != -1) whichr[1]=true;
if(row2.indexOf(words[i].substring(j,j+1)) != -1) whichr[2]=true;
}
for(boolean ww : whichr){
if(ww) count++;
}
if(count==1)
res.add(words[i]);
}
String[] ares = new String[res.size()];
for(int i=0;i<res.size();i++){
ares[i]=res.get(i);
}
for(String str : ares)
System.out.println(str);
return ares;
}
}
一些坑:
1、对数组,用arr.length
2、对String,用str.length()
3、下面这个赋值操作:
for(int z=0;z< whichr.length;z++){
whichr[z]=false;
}
一开始我是用这样:
for(boolean ww2 : whichr){
ww2=false;
}
这样是不对的,which里面的值没有被更新。
4、ArrayList的toArray
String[] array =new String[list.size()];
list.toArray(array);
5、获取String里面的单独的char的方法
char[] strBit = word.toCharArray(); //变成char的数组
char a1=word.charAt(j);
另一种方法,用map
public static String[] findWords2(String[] words) {
String[] Str = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
Map<Character,Integer> map = new HashMap<>();
for(int i=0; i<Str.length; i++) {
for(char c : Str[i].toCharArray()) {
map.put(c, i);
}
}
int index = 0;
List<String> res = new ArrayList<>();
for(String word : words) {
if (word.equals("")) continue;
index = map.get(word.toUpperCase().toCharArray()[0]);
for(char c : word.toUpperCase().toCharArray()) {
if(map.get(c) != index) {
index = -1;//不用设置flag 直接把index设为-1即可
break;
}
}
if(index != -1) res.add(word);
}
return res.toArray(new String[res.size()]);
}