确实是非常无聊的题,思考没有难度,就是要小心,比如大小写之类。
以下代码丑到我不想看。另外,真不应该在周末昏昏欲睡的下午状态不好的时候写题目。
public String[] findWords(String[] words) {
Map<Character , Integer> row1 = new HashMap<>();
Map<Character , Integer> row2 = new HashMap<>();
Map<Character , Integer> row3 = new HashMap<>();
row1.put('q', 1);
row1.put('w', 1);
row1.put('e', 1);
row1.put('r', 1);
row1.put('t', 1);
row1.put('y', 1);
row1.put('u', 1);
row1.put('i', 1);
row1.put('o', 1);
row1.put('p', 1);
row2.put('a', 2);
row2.put('s', 2);
row2.put('d', 2);
row2.put('f', 2);
row2.put('g', 2);
row2.put('h', 2);
row2.put('j', 2);
row2.put('k', 2);
row2.put('l', 2);
row3.put('z', 3);
row3.put('x', 3);
row3.put('c', 3);
row3.put('v', 3);
row3.put('b', 3);
row3.put('n', 3);
row3.put('m', 3);
List<String> res = new ArrayList<>();
for (int i = 0 ; i < words.length ; i ++){
String word = words[i];
if (word.length() == 0) continue;
String c = (word.charAt(0) + "").toLowerCase() ;
char cc = c.toCharArray()[0];
int row = row1.get(cc) != null ? row1.get(cc) : (row2.get(cc)!= null ? row2.get(cc) : row3.get(cc));
int j = 1;
for (; j < word.length() ; j ++){
String c2 = (word.charAt(j) + "").toLowerCase() ;
char cc2 = c2.toCharArray()[0];
int tem = row1.get(cc2) != null ? row1.get(cc2) : (row2.get(cc2)!= null ? row2.get(cc2) : row3.get(cc2));
if (tem!=row){
break;
}
}
if (j == word.length()){
res.add(word);
}
}
String[] strings = new String[res.size()];
return res.toArray(strings) ;
}
稍微好看点的样子,用String做key而不是char,可以直接用toUpperCase:
public class Solution {
public String[] findWords(String[] words) {
String[] strs = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i<strs.length; i++){
for(char c: strs[i].toCharArray()){
map.put(c, i);//put <char, rowIndex> pair into the map
}
}
List<String> res = new LinkedList<>();
for(String w: words){
if(w.equals("")) continue;
int index = map.get(w.toUpperCase().charAt(0));
for(char c: w.toUpperCase().toCharArray()){
if(map.get(c)!=index){
index = -1; //don't need a boolean flag.
break;
}
}
if(index!=-1) res.add(w);//if index != -1, this is a valid string
}
return res.toArray(new String[0]);
}
}