#leetcode#500 Keyboard Row
来源:互联网 发布:女性 音乐家 知乎 编辑:程序博客网 时间:2024/05/22 11:47
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.
======================================================================================================
没有太动脑子想一些简洁的代码, 通过这个题发现自己对 Arrays.asList(), list.toArray(), hashset.addAll() 这几个method用的不熟
public class Solution { public String[] findWords(String[] words) { if(words == null || words.length == 0) return new String[]{}; List<String> res = new ArrayList<>(); Set<Character> set1 = new HashSet<>(); Set<Character> set2 = new HashSet<>(); Set<Character> set3 = new HashSet<>(); Character[] arr1 = new Character[]{'Q','q','W','w','E','e','R','r','T','t','Y','y','U','u','I','i','O','o','P','p'}; Character[] arr2 = new Character[]{'A','a','S','s','D','d','F','f','G','g','H','h','J','j','K','k','L','l'}; Character[] arr3 = new Character[]{'Z','z','X','x','C','c','V','v','B','b','N','n','M','m'}; set1.addAll(Arrays.asList(arr1)); set2.addAll(Arrays.asList(arr2)); set3.addAll(Arrays.asList(arr3)); for(String s : words){ boolean row1 = false; boolean row2 = false; boolean row3 = false; for(int i = 0; i < s.length(); i++){ Character c = s.charAt(i); if(set1.contains(c)) row1 = true; else if(set2.contains(c)) row2 = true; else if(set3.contains(c)) row3 = true; } if((row1 && !row2 && ! row3) || (!row1 && row2 && !row3) || (!row1 && !row2 && row3)){ res.add(s); } } // String[] result = new String[res.size()]; //also works // return res.toArray(result); return res.toArray(new String[0]); }}
阅读全文
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 C++
- leetcode 500 Keyboard Row Add to List
- Leetcode-500. Keyboard Row
- 【Leetcode】500. Keyboard Row
- 【LeetCode】500. Keyboard Row
- LeetCode 500. Keyboard Row
- LeetCode 500. Keyboard Row
- [leetcode]554. Brick Wall
- Regular expressions are commonly used
- maven之clean、install命令
- 爬虫中使用的数据结构
- ArcGIS Earth数据小析
- #leetcode#500 Keyboard Row
- shader
- [提交答案题] UOJ #109 【APIO2013】TASKSAUTHOR
- shader2
- PAT 1001
- 一个神奇的???whatever~~
- PAT 1002
- Build VIM&GVIM Executables on Windows
- leetcode-11. Container With Most Water