问题描述
问题链接:https://leetcode.com/problems/keyboard-row/#/description
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.
我的代码
这题的思路非常简单,我就直接贴代码了。遇到的坑主要是API不记得了。以后会把学过的Trick整理出来,方便今后复习。
public class Solution {
private static String rowOne = "qwertyuiopQWERTYUIOP";
private static String rowTwo = "asdfghjklASDFGHJKL";
private static String rowThree = "zxcvbnmZXCVBNM";
public String[] findWords(String[] words) {
/*
思路是首先创建3个列表,分别包含键盘中3行的字母的大小写,
然后遍历输入的单词,判断每个单词的所有字母是不是都出现在同一个列表中,
如果是,那么这个单词符合要求,否则不符合要求
*/
List<String> wordList = new ArrayList<String>();
for(String word : words){
if(canInput(word)){
wordList.add(word);
}
}
String[] results = new String[wordList.size()];
return wordList.toArray(results);
}
private boolean canInput(String word){
char c = word.charAt(0);
String checkRow = rowThree;
if(rowOne.indexOf(c) >= 0){
checkRow = rowOne;
}else if(rowTwo.indexOf(c) >= 0){
checkRow = rowTwo;
}
for(int i = 1; i < word.length(); i++){
char ch = word.charAt(i);
if(checkRow.indexOf(ch) < 0){
return false;
}
}
return true;
}
}
这次我打败了98.38%的Java代码!哈哈哈好开心。
讨论区
来,再到讨论区看看大神们的代码。
Short Easy Java with Explanation
链接地址:https://discuss.leetcode.com/topic/77773/short-easy-java-with-explanation
public string[] FindWords(string[] words)
{
int[] row1 = ToCountArr("qwertyuiop");
int[] row2 = ToCountArr("asdfghjkl");
int[] row3 = ToCountArr("zxcvbnm");
return words.Where(w => All(row1, w) || All(row2, w) || All(row3, w)).ToArray();
}
public int[] ToCountArr(string s)
{
int[] arr = new int[26];
foreach (char c in s)
{
arr[c - 'a'] = 1;
}
return arr;
}
public bool All(int[] row, string input)
{
foreach (char c in input.ToLower())
{
if (row[c-'a'] == 0) return false;
}
return true;
}