0500. Keyboard Row

0500. Keyboard Row #

题目 #

  • 给定字符串数组 words ,返回可以使用在 美式键盘 同一行的字母打印出来的单词。
  • 美式键盘 中:
    • 第一行由字符 "qwertyuiop" 组成。
    • 第二行由字符 "asdfghjkl" 组成。
    • 第三行由字符 "zxcvbnm" 组成。

思路 #

模拟+打表 #

代码 #

模拟+打表 #

class Solution {
    public void mapping (int[] qwerty) {
        qwerty['q'-'a'] = 0;
        qwerty['w'-'a'] = 0;
        qwerty['e'-'a'] = 0;
        qwerty['r'-'a'] = 0;
        qwerty['t'-'a'] = 0;
        qwerty['y'-'a'] = 0;
        qwerty['u'-'a'] = 0;
        qwerty['i'-'a'] = 0;
        qwerty['o'-'a'] = 0;
        qwerty['p'-'a'] = 0;

        qwerty['a'-'a'] = 1;
        qwerty['s'-'a'] = 1;
        qwerty['d'-'a'] = 1;
        qwerty['f'-'a'] = 1;
        qwerty['g'-'a'] = 1;
        qwerty['h'-'a'] = 1;
        qwerty['j'-'a'] = 1;
        qwerty['k'-'a'] = 1;
        qwerty['l'-'a'] = 1;

        qwerty['z'-'a'] = 2;
        qwerty['x'-'a'] = 2;
        qwerty['c'-'a'] = 2;
        qwerty['v'-'a'] = 2;
        qwerty['b'-'a'] = 2;
        qwerty['n'-'a'] = 2;
        qwerty['m'-'a'] = 2;
    }
    
    public String[] findWords(String[] words) {
        int[] qwerty = new int[26];
        mapping(qwerty);

        List<String> ans = new ArrayList<>();
        for (String word: words) {
            boolean ok = true;
            for (int i = 0; i < word.length(); i++) {
                if (qwerty[word.toLowerCase().charAt(i) - 'a'] != qwerty[word.toLowerCase().charAt(0) - 'a']) ok = false;
            }
            if (ok) ans.add(word);
        }

        return ans.toArray(new String[ans.size()]);
    }
}