500. Keyboard Row
来源:互联网 发布:入门单板吉他推荐 知乎 编辑:程序博客网 时间:2024/05/16 17:35
题目
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"]
解法
public class Solution { public String[] findWords(String[] words) { HashMap<Character, Integer> map = new HashMap<>(); ArrayList<String> list = new ArrayList<>(); //字符表加入到map中,每一行用不同index表示 String[] strs = new String[]{"qwertyuiop","asdfghjkl","zxcvbnm"}; for(int i = 0; i < strs.length; i ++){ for(char c : strs[i].toCharArray()){ map.put(c, i); } } //判断单词中每个字符是否和首字符是否在同一行 for(String w : words){ int index = map.get(w.toLowerCase().charAt(0)); for(char c : w.toLowerCase().toCharArray()){ if(map.get(c)!=index){ index = -1; break; } } if(index != -1) list.add(w); } return list.toArray(new String[0]); }}
解法分析:将键盘每一行字符存在map中,用0、1、2来表示行。对每个单词分析,如果有一个单词和首字符不在同一行,则退出循环;否则都可以用同一行表示。
简单解法(不太会):
public String[] findWords(String[] words) { return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")).toArray(String[]::new);}分析:运用了函数式编程和正则表达式
0 0
- Leetcode-500. Keyboard Row
- 【Leetcode】500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row
- LeetCode 500. Keyboard Row
- 500. Keyboard Row
- 500. Keyboard Row (E)
- 500. Keyboard Row
- 500. Keyboard Row
- leetcode 500. Keyboard Row
- 500. Keyboard Row
- [LeetCode]500. Keyboard Row
- 500. Keyboard Row
- android sdcard存储方案一(基于fuse文件系统)
- python __set__ __get__ 等解释
- android sdcard存储方案二(基于fuse文件系统)
- 使用MAME的Lua引擎修改内存数据
- 41.android广播-监控应用的状态
- 500. Keyboard Row
- 【C++ 学习笔记】防止头文件二次编译总结
- 获取短信内容
- 帝国cms常用标签
- HDU1072 Nightmare(dfs)
- 反射6
- android sdcard存储方案三(基于fuse文件系统):
- C++基础之返回数组
- 电话拦截