LeetCode-Keyboard Row

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82720855

Description:
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.

题意:给定一个字符串数组,找出数组中有哪些字符串中的所有字符在键盘上面是同一行;

解法:要判断字符串中的所有字符是否在同一行,我们可以创建一张字母在键盘上的映射表,表中存储字母在键盘上的行数,这样只需要根据这张表遍历字符串中的所有字符,判断其是否是同一行即可;

Java
class Solution {
    public String[] findWords(String[] words) {
        if (words.length == 0) {
            return new String[] {};
        }
        //定义字母在键盘上的行位置
        int[] keyboard = new int[] {1, 2, 2, 1, 3, 1, 1, 1, 3, 1, 1, 1, 2, 2,
            3, 3, 3, 3, 1, 3, 3, 2, 3, 2, 3, 2};
        StringBuilder sb = new StringBuilder();
        for (String word : words) {
            if (oneRows(keyboard, word.toLowerCase())) {
                sb.append(word + " ");
            }
        }
        return sb.toString().length() == 0 ? new String[] {} : sb.toString().trim().split("\u0020");
    }

    //判断字符串中的每个字符是否都在同一行上
    private boolean oneRows(int[] keyboard, String s) {
        int row = keyboard[s.charAt(0) - 'a'];
        for (int i = 1; i < s.length(); i++) {
            if (keyboard[s.charAt(i) - 'a'] != row) {
                return false;
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82720855
Row