键盘行
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。
键盘如下图所示:
示例1:
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
注意:
- 你可以重复使用键盘上同一字符。
- 你可以假设输入的字符串将只包含字母。
通过此题掌握哈希表的知识
题目分析:
题目的意思是用给出的字符串去与键盘上的一串字符串去比较,看组成字符串的字符是不是全部属于键盘上的某一行;所以自然想到了用哈希表,把键盘上属于一行的字符作为“键”存储,然后用给定的字符串去哈希表里面查找。
代码实现:
public String[] findWords(String[] words) { HashMap<Character, Integer> hashMap = new HashMap<>(); List<String> list = new ArrayList<>(); String[] s = {"qwertyuiop", "asdfghjkl", "zxcvbnm"}; for (int i = 0; i < s.length; i++) { char[] ch = s[i].toCharArray(); for (int j = 0; j < ch.length; j++) { hashMap.put(ch[j], i); } } for (int i = 0; i < words.length; i++) { String str = words[i].toLowerCase() ; char[] ch = str.toCharArray(); int x = hashMap.get(ch[0]); boolean flag = true; for (int j = 1; j < ch.length; j++) { if (hashMap.get(ch[j]) != x) { flag = false; break; } } if (flag) list.add(words[i]); } words = new String[list.size()]; int i = 0; for (String ss : list) { words[i] = ss; i++; } return words; }
以主函数中给定的字符串数组{“Hello”,“Alaska”,“Dad”,“Peace”}为例:
-
在第一个for循环中,将“qwertyuiop", “asdfghjkl”, "zxcvbnm"作为”键“,对应的“值”为0,1,2;这些键值对存入了哈希表中;**
-
对于字符串”Hello“;x的值为哈希表中键h对应的值1,即x = 1,然后扫描h后面的字符,e、l、o,看其对应的值是不是1,e和o对应的值为0,所以返回false;**
-
对于字符串”Alaska“;x的值为哈希表中键a对应的值0,即x = 0,然后扫描a后面的字符,l、a、s、k、a,看其对应的值是不是0,对应的值都为0,所以返回true,此字符串加入输出列表;**
-
对于字符串”Dad“;x的值为哈希表中键d对应的值1,即x = 1,然后扫描d后面的字符,a、d,看其对应的值是不是1,对应的值都为1,所以返回true,此字符串加入输出列表;**
-
对于字符串”Peace“;x的值为哈希表中键p对应的值0,即x = 0,然后扫描p后面的字符,e、a、c、e,看其对应的值是不是0,a对应的值为1,c对应的值为2,所以返回false;**
-
所以最后输出的结果为“Alaska”和“Dad”**
主函数:
public static void main(String[] args) { H1 h = new H1(); String[] s = h.findWords(new String[]{"Hello", "Alaska", "Dad", "Peace"}); for (int i = 0; i < s.length; i++) { System.out.print(s[i] + " "); } }
运行结果:
Alaska Dad