【LeetCode】500. Keyboard Row
来源:互联网 发布:2017学校网络改造方案 编辑:程序博客网 时间:2024/06/06 02:32
问题描述
问题链接: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; }
1 0
- Leetcode-500. Keyboard Row
- 【Leetcode】500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- LeetCode 500. Keyboard Row
- LeetCode 500. Keyboard Row
- leetcode 500. Keyboard Row
- [LeetCode]500. Keyboard Row
- LeetCode | 500. Keyboard Row
- [LeetCode]500. Keyboard Row
- LeetCode 500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- Leetcode 500. Keyboard Row
- LeetCode 500. Keyboard Row
- LeetCode 500. Keyboard Row
- [leetcode]: 500. Keyboard Row
- leetcode 500. Keyboard Row
- [leetcode] 500. Keyboard Row
- LeetCode 500. Keyboard Row
- vue组件最佳实践
- JNI交叉编译_NDK插件
- androidStudio升级到2.3之后新建Activity布局变成了约束(ConstraintLayout)布局
- 读取网络时间
- linux 设置环境变量的方法
- 【LeetCode】500. Keyboard Row
- 很详细的事件分发机制 转载一下
- JavaScript正则表达式的分组匹配详解
- Struts2配置详解_配置Action
- 单点登录SSO的实现原理
- 判断cpu是不是支持SSE42指令集
- oracle jdbc 分批抓取查询FetchSize(100)
- Sprint注入和bean的自动装配以及Autowired的用法
- 【大数据干货】轻松处理每天2TB的日志数据,支撑运营团队进行大数据分析挖掘,随时洞察用户个性化需求。