1、题目:
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:
1. Input: ["Hello", "Alaska", "Dad", "Peace"] 2. Output: ["Alaska", "Dad"]
2、代码实现:
import java.util.ArrayList; public class Solution { public ArrayList<String> resultList; //检验这个字符串是否全在同一行 public boolean check(String s1, String s2) { if (s1 == null) { return false; } for (int i = 0; i < s1.length(); ++i) { if (s2.indexOf(s1.charAt(i)) == -1) { return false; } } return true; } public String[] findWords(String[] words) { //检验字符串数组是否都为null if (words == null) { return null; } int length = words.length; String s1 = "qwertyuiop"; String s2 = "asdfghjkl"; String s3 = "zxcvbnm"; resultList = new ArrayList<String>(); //判断每次 for (int i = 0; i < length; ++i) { String lowerStr = words[i].toLowerCase(); if (lowerStr != "") { if (s1.indexOf(lowerStr.charAt(0)) != -1) { if(check(lowerStr, s1)) resultList.add(words[i]); } if (s2.indexOf(lowerStr.charAt(0)) != -1) { if(check(lowerStr, s2)) resultList.add(words[i]); } if (s3.indexOf(lowerStr.charAt(0)) != -1) { if(check(lowerStr, s3)) resultList.add(words[i]); } } } String[] strArr = new String[resultList.size()]; resultList.toArray(strArr); return strArr; } }
3、遇到的问题:
特么我一开始把在if后面加了
if(check(lowerStr, s1));
导致所有的数据都加进去了,以后要注意,不要乱鸡吧写,在if后面加上;