leetcode 500. Keyboard Row
来源:互联网 发布:知轩藏书下载 编辑:程序博客网 时间:2024/06/07 02:27
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.
import java.util.ArrayList;import java.util.Arrays;public class Keyboard_Row_500 {char[][] keywords=new char[][]{{'q','w','e','r','t','y','u','i','o','p'},{'a','s','d','f','g','h','j','k','l'},{'z','x','c','v','b','n','m'}};private boolean isOK(String word){boolean isOK=true;word=word.toLowerCase();char[] chars=word.toCharArray();char firstChar=chars[0];int type=2;for(int i=0;i<keywords[0].length;i++){if(keywords[0][i]==firstChar){type=0;break;}}if(type!=1){for(int i=0;i<keywords[1].length;i++){if(keywords[1][i]==firstChar){type=1;break;}}}for(int i=1;i<chars.length;i++){char thisChar=chars[i];boolean isContains=false;for(int j=0;j<keywords[type].length;j++){if(thisChar==keywords[type][j]){isContains=true;break;}}if(isContains==false){isOK=false;break;}}return isOK;}public String[] findWords(String[] words) {ArrayList<String> s = new ArrayList<String>();for(int i=0;i<words.length;i++){if(isOK(words[i])==true){s.add(words[i]);}}String[] result=new String[s.size()];for(int i=0;i<s.size();i++){result[i]=s.get(i);}return result;}public static void main(String[] args) {// TODO Auto-generated method stubKeyboard_Row_500 k = new Keyboard_Row_500();String[] words=new String[]{"Hello", "Alaska", "Dad", "Peace"};System.out.println(Arrays.toString(k.findWords(words)));}}然后看到大神有一行的解答:
public String[] findWords(String[] words) { return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")).toArray(String[]::new);}这真是。。。正则大法好!
不过正则性能不行啊,它这个跑29个case用了91ms,我的方法只需要4ms...而且他里面用了Stream库和一些我不太懂的函数。。。果然大神用的方法都比较高级!
0 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
- angular-filter自定义过滤器运行顺序
- ios 合并静态库.a文件
- 前端笔试重点(3)
- 【动态规划】完全背包
- 第十周 简单的动态规划
- leetcode 500. Keyboard Row
- Arrays.copyOfRange的用法
- 学习HTML
- 同步和异步+阻塞和非阻塞
- git使用小结
- windows server 2012 IE增强的安全配置如何关闭
- mac 下从设置启动mysql 失败,“Warning:The /usr/local/mysql/data directory is not owned by the 'mysql' or '_mys
- 【一步步学OpenGL 27】 -《公告牌技术与几何着色器》
- poj 3069 Saruman's Army