终于做出来一个题。首先贴自己的代码。
public class Solution {
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"};
public boolean isContainRow1(String words){
for(int i=0;i<10;i++) {
if (words.contains(row1[i])) return true;
}
return false;
}
public boolean isContainRow2(String words){
for(int i=0;i<9;i++) {
if (words.contains(row2[i])) return true;
}
return false;
}
public boolean isContainRow3(String words){
for(int i=0;i<7;i++) {
if (words.contains(row3[i])) return true;
}
return false;
}
public String[] findWords(String[] words) {
List<String> list = new ArrayList<String>();
for(int i =0;i<words.length;i++) {
String cur = words[i];
if(
((isContainRow1(cur))&&(!isContainRow2(cur))&&(!isContainRow3(cur)))
|| ((isContainRow2(cur))&&(!isContainRow1(cur))&&(!isContainRow3(cur)))
|| ((isContainRow3(cur))&&(!isContainRow1(cur))&&(!isContainRow2(cur)))
)
list.add(cur);
}
return list.toArray(new String[list.size()]);
}
}
其实最后也卡住在返回String[ ]上面,查过才知道List的转换可以解决返回字符串数组。
后面查询Disscussion,可以进行优化:统计每个单词的起始字母,然后再查看后面的字母是否与其属于同一行。
两种思路:
- 一:使用字符串
在键盘的字符串数组key[ ] 里,查询单词的字母是否在里面,可用!contains()或者indexOf() == -1来确定。使用flag来确定是否把当前单词加到结果里面。
int currentRow = 0;
boolean found = true;
for(String s : words)
{
currentRow = getCurrentRow(s.charAt(0));
found = true;
for(char c: s.toCharArray())
{
if(rows[currentRow].indexOf(c) == -1)
{
found = false;
break;
}
}
if(found)
result.add(s);
}
- 二:使用别的数据结构