leetcode500 Keyboard Row Java
来源:互联网 发布:php在线编辑器源代码 编辑:程序博客网 时间:2024/06/06 01:09
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.
解法1
public class Solution { public String[] findWords(String[] words) { List<String> oneRowWords = new ArrayList<String>(); String[] keyboard = {"qwertyuiop","asdfghjkl","zxcvbnm"}; for(String word : words) { String realWord = word; word = word.toLowerCase();//每个字母变为小写 char[] strBit = word.toCharArray(); int count = 0; for(char ch : strBit) { if(keyboard[0].indexOf(strBit[0]) != -1) {//第一个字母在第一排 if(keyboard[0].indexOf(ch) == -1) {//其他字母必须也在第一排 否则跳过 break; } }else if(keyboard[1].indexOf(strBit[0]) != -1) {//第一个字母在第二排 if(keyboard[1].indexOf(ch) == -1) { break; } }else if(keyboard[2].indexOf(strBit[0]) != -1) {//第一个字母在第三排 if(keyboard[2].indexOf(ch) == -1) { break; } } count ++; } if(count == strBit.length) { oneRowWords.add(realWord); } } String[] oneRowWordsArray = new String[oneRowWords.size()]; for(int i=0; i<oneRowWords.size(); i++){ oneRowWordsArray[i] = oneRowWords.get(i); } return oneRowWordsArray; }}
解法2
把键盘中的字母和其所在行数放到map。
public static String[] findWords2(String[] words) { String[] Str = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"}; Map<Character,Integer> map = new HashMap<>(); for(int i=0; i<Str.length; i++) { for(char c : Str[i].toCharArray()) { map.put(c, i); } } int index = 0; List<String> res = new ArrayList<>(); for(String word : words) { if (word.equals("")) continue; index = map.get(word.toUpperCase().toCharArray()[0]); for(char c : word.toUpperCase().toCharArray()) { if(map.get(c) != index) { index = -1;//不用设置flag 直接把index设为-1即可 break; } } if(index != -1) res.add(word); } return res.toArray(new String[res.size()]); }
1 0
- leetcode500 Keyboard Row Java
- leetcode500: Keyboard Row
- Leetcode500. Keyboard Row
- leetcode500. Keyboard Row
- LeetCode500. Keyboard Row
- Leetcode500. Keyboard Row
- python--leetcode500. Keyboard Row
- 14.leetCode500:keyboard row
- LeetCode500. Keyboard Row我的C++解法
- LeetCode 500. Keyboard Row-Java
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- Keyboard Row
- java发送qq邮件
- 浅谈RxJava与多线程并发
- Samba服务器配置 (REDHAT6.4)
- Facade Pattern
- java中的自动装箱和拆箱
- leetcode500 Keyboard Row Java
- 为经典版eclipse增加web and JavaEE插件
- Struts2拦截器实现异常处理机制
- 0303
- 朝花夕拾-致我的2016
- python 多excel导入到mysql中去
- java异常
- 欢迎使用CSDN-markdown编辑器
- javascript学习(一)——第一部分 JavaScript语言核心