500. Keyboard Row
来源:互联网 发布:vb sum函数 编辑:程序博客网 时间:2024/06/06 02:15
问题描述:给你一串字,判断这些字能否用美式键盘布局上同一行的字母打出来。
思路:写上52行的case when进行判断,想想都觉得美妙,所以直接看答案了。
最佳答案:
public String[] findWords(String[] words) { String s1 = "qwertyuiop"; String s2 = "asdfghjkl"; String s3 = "zxcvbnm"; int[] map = new int[26]; for (int i = 0; i < s1.length(); i++) { map[s1.charAt(i) - 'a'] = 0; } for (int i = 0; i < s2.length(); i++) { map[s2.charAt(i) - 'a'] = 1; } for (int i = 0; i < s3.length(); i++) { map[s3.charAt(i) - 'a'] = 2; } ArrayList<String> res = new ArrayList<String>(); for (String w : words) { if (w.length() == 0) continue; String s = w.toLowerCase(); int row = map[s.charAt(0) - 'a']; boolean valid = true; for (int i = 1; i < s.length(); i++) { if (map[s.charAt(i) - 'a'] != row) { valid = false; break; } } if (valid) res.add(w); } return res.toArray(new String[res.size()]); }
可以不用那么多的case when 直接使用map的哈希值快速取数。
另一个不错的答案如下:
public String[] findWords(String[] words) { String keyboardRegex = "[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*"; return Stream.of(words) .filter(word -> word.toLowerCase().matches(keyboardRegex)) .toArray(String[]::new); }
很简洁,一开始完全看不懂。用到了jdk1.8中的lamda表达式,1.6版本的编程思想都还没看完。知识库又要更新了。
阅读全文
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
- 解决sink = gst_element_factory_make ("alsasink", "alsa-output");sink为NULL问题
- VMware
- 迭代器
- python_安装模块后出错:无法启动程序丢失vcom140.dll
- JS两个数组去重
- 500. Keyboard Row
- C++中动多态实现之虚函数与虚表指针
- 习题8.3
- Linux学习之路-基本命令(二)
- a+=1与a=a+1的区别
- c++实现植物大战僵尸修改器
- Retrofit上传文件
- go安装配置
- DeptController(controller)