Keyboard Row

1. Title
500. Keyboard Row
2. Http address
https://leetcode.com/problems/keyboard-row/?tab=Description
3. The question

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:

Input: ["Hello", "Alaska", "Dad", "Peace"]
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.

4. Code

public class Solution {
    public String[] findWords(String[] words) {
        
        Set<Character> hashSet1 = new HashSet<Character>();
        Set<Character> hashSet2 = new HashSet<Character>();
        Set<Character> hashSet3 = new HashSet<Character>();
        Set sets[] = new HashSet[3];
        sets[0] = hashSet1;
        sets[1] = hashSet2;
        sets[2] = hashSet3;
        hashSet1.add('Q');
        hashSet1.add('W');
        hashSet1.add('E');
        hashSet1.add('R');
        hashSet1.add('T');
        hashSet1.add('Y');
        hashSet1.add('U');
        hashSet1.add('I');
        hashSet1.add('O');
        hashSet1.add('P');

        hashSet2.add('A');
        hashSet2.add('S');
        hashSet2.add('D');
        hashSet2.add('F');
        hashSet2.add('G');
        hashSet2.add('H');
        hashSet2.add('J');
        hashSet2.add('K');
        hashSet2.add('L');

        hashSet3.add('Z');
        hashSet3.add('X');
        hashSet3.add('C');
        hashSet3.add('V');
        hashSet3.add('B');
        hashSet3.add('N');
        hashSet3.add('M');

        if (words == null || words.length <= 0) {
            return new String[0];
        }

        int len = words.length;

        String[] re = new String[len];
        int index = 0;
        for (int i = 0; i < len; i++) {
            String word = words[i].toUpperCase();
            int wlen = word.length();
            int tag = 0;
            int j = 0;
            if (sets[0].contains(word.charAt(0))) {
                tag = 0;
            } else if (sets[1].contains(word.charAt(0))) {
                tag = 1;
            } else {
                tag = 2;
            }
            j++;
            while (j < wlen) {
                if (!sets[tag].contains(word.charAt(j))) {
                    break;
                }
                j++;
            }
            if (j == wlen) {
                re[index++] = words[i];
            }
        }
        String[] res = new String[index];
        for (int i = 0; i < index; i++) {
            res[i] = re[i];
        }
        return res;
    
    }
}
原文地址:https://www.cnblogs.com/ordili/p/6516508.html