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.
题目标签:Hash Table
题目给了我们一个words array,让我们判断每一个word 中的 chars 是否都来自于键盘上的同一行。
利用HashMap 把键盘上的3行 chars 保存:char 当作 key;行数 当作 value。
接着遍历words,检查每一个word。
Java Solution:
Runtime beats 68.36%
完成日期:06/07/2017
关键词:HashMap
关键点:char 当作 key;行数 当作 value
1 class Solution 2 { 3 public String[] findWords(String[] words) 4 { 5 HashMap<Character, Integer> map = new HashMap<>(); 6 List<String> resList = new ArrayList<>(); 7 8 String row1 = "qwertyuiop"; 9 String row2 = "asdfghjkl"; 10 String row3 = "zxcvbnm"; 11 12 // set up the map 13 for(char c: row1.toCharArray()) 14 map.put(c, 1); 15 16 for(char c: row2.toCharArray()) 17 map.put(c, 2); 18 19 for(char c: row3.toCharArray()) 20 map.put(c, 3); 21 22 23 // iterate each word to check all chars are from one row 24 for(String word: words) 25 { 26 char[] wordChars = word.toLowerCase().toCharArray(); 27 int rowNumber = map.get(wordChars[0]); 28 boolean add = true; 29 30 for(char c: wordChars) 31 { 32 if(rowNumber != map.get(c)) 33 { 34 add = false; 35 break; 36 } 37 38 } 39 40 if(add) 41 resList.add(word); 42 } 43 44 String[] res = new String[resList.size()]; 45 46 for(int i=0; i<res.length; i++) 47 res[i] = resList.get(i); 48 49 return res; 50 } 51 }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List