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

    xiaoxiao2021-03-25  49

    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.

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

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

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

    public String[] findWords(String[] words) { 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 }; String[] temp = new String[words.length]; int index = 0; for (String word : words) { char[] chars = word.toLowerCase().toCharArray(); int len = chars.length; if (len == 0) break; int row = keyboard[chars[0] - 'a']; int i; for (i = 0; i < len; i++) { if (keyboard[chars[i] - 'a'] != row) break; } if (i == len) temp[index++] = word; } String[] res = new String[index]; for(int i=0;i<index;i++) res[i] = temp[i]; return res; }

    转载请注明原文地址: https://ju.6miu.com/read-36641.html

    最新回复(0)