500. Keyboard Row(判断单词能否由键盘上的某一行字符表示)

阳光穿透心脏的1/2处 2022-09-28 14:26 96阅读 0赞

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.

American keyboard

Example 1:

  1. Input: ["Hello", "Alaska", "Dad", "Peace"]
  2. Output: ["Alaska", "Dad"]

Note:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

题目大意:给定一组字符串,判断其中哪些可以由键盘上的某一行字母表示,输出满足条件的字符串所构成的字符串数组。

解题思路:定义一个长度为26的整型数组keyboard,keyboard[i]表示字符‘a’+1属于键盘上的第几行字母(第一行,第二行,或者第三行)。对每一个字符串进行判断,如果每一个字符都在同一行,则该字符串满足条件,否则不满足。

代码如下:(3ms,beats 82.87%)

  1. public String[] findWords(String[] words) {
  2. int[] keyboard = new int[] { 2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, 3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3 };
  3. String[] temp = new String[words.length];
  4. int index = 0;
  5. for (String word : words) {
  6. char[] chars = word.toLowerCase().toCharArray();
  7. int len = chars.length;
  8. if (len == 0)
  9. break;
  10. int row = keyboard[chars[0] - 'a'];
  11. int i;
  12. for (i = 0; i < len; i++) {
  13. if (keyboard[chars[i] - 'a'] != row)
  14. break;
  15. }
  16. if (i == len)
  17. temp[index++] = word;
  18. }
  19. String[] res = new String[index];
  20. for(int i=0;i<index;i++)
  21. res[i] = temp[i];
  22. return res;
  23. }

发表评论

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

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

相关阅读

    相关 500. Keyboard Row

    [原题链接][Link 1] 这道题如果是自己做的话,应该就是遍历了。 但是在discuss区有个非常巧妙的做法,这里就贴上来 public class P50