leetcode 500. 键盘行(Java版)

逃离我推掉我的手 2023-01-18 15:19 108阅读 0赞

题目

https://leetcode-cn.com/problems/keyboard-row/
在这里插入图片描述

题解

对于每一个单词,先确定所在键盘行数,然后验证后面的字母是否在同一行。

  1. class Solution {
  2. public static String[] findWords(String[] words) {
  3. HashMap<Character, Integer> map = new HashMap<>();
  4. map.put('q', 1);
  5. map.put('w', 1);
  6. map.put('e', 1);
  7. map.put('r', 1);
  8. map.put('t', 1);
  9. map.put('y', 1);
  10. map.put('u', 1);
  11. map.put('i', 1);
  12. map.put('o', 1);
  13. map.put('p', 1);
  14. map.put('a', 2);
  15. map.put('s', 2);
  16. map.put('d', 2);
  17. map.put('f', 2);
  18. map.put('g', 2);
  19. map.put('h', 2);
  20. map.put('j', 2);
  21. map.put('k', 2);
  22. map.put('l', 2);
  23. map.put('z', 3);
  24. map.put('x', 3);
  25. map.put('c', 3);
  26. map.put('v', 3);
  27. map.put('b', 3);
  28. map.put('n', 3);
  29. map.put('m', 3);
  30. List<String> list = new ArrayList<String>();
  31. for (String word : words) {
  32. char[] chars = word.toLowerCase().toCharArray();
  33. int line = map.get(chars[0]);
  34. int i;
  35. for (i = 0; i < chars.length; i++) {
  36. if (map.get(chars[i]) != line) break;
  37. }
  38. if (i == chars.length) list.add(word);
  39. }
  40. String[] resultArray = new String[list.size()];
  41. resultArray = list.toArray(resultArray);
  42. return resultArray;
  43. }
  44. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,108人围观)

还没有评论,来说两句吧...

相关阅读