leetcode刷题:键盘行

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

这里写图片描述

示例1:

输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]

注意:

你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。

java 代码


classclass  SolutionSolution  {
    {     publicpublic String[] findWords(String[] words) {
         String[] find int[] ws = new int[255];
        initWs(ws);

        List<String> res = new ArrayList<>();

        for (String str : words) {

            String temp = str.toLowerCase();

            int local = ws[temp.charAt(0)]; 

            boolean is = true;
            for (char c : temp.toCharArray()) {
                if (ws[c] != local) {
                    is = false;
                    break;
                }
            }

            if (is) {
                res.add(str);
            }
        }

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


    private void initWs(int[] ws) {

        ws['q'] = 2;
        ws['w'] = 2;
        ws['e'] = 2;
        ws['r'] = 2;
        ws['t'] = 2;
        ws['y'] = 2;
        ws['u'] = 2;
        ws['i'] = 2;
        ws['o'] = 2;
        ws['p'] = 2;

        ws['a'] = 1;
        ws['s'] = 1;
        ws['d'] = 1;
        ws['f'] = 1;
        ws['g'] = 1;
        ws['h'] = 1;
        ws['j'] = 1;
        ws['k'] = 1;
        ws['l'] = 1;
    }

}

猜你喜欢

转载自blog.csdn.net/sunyuhua_keyboard/article/details/80916630
今日推荐