LeetCode-每日一题 500. 键盘行 [Java实现] [极速]

给你一个字符串数组 words ,只返回可以使用在 美式键盘 同一行的字母打印出来的单词。键盘如下图所示。

美式键盘 中:

  • 第一行由字符 "qwertyuiop" 组成。
  • 第二行由字符 "asdfghjkl" 组成。
  • 第三行由字符 "zxcvbnm" 组成。

American keyboard

示例 1

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


方法一:哈希表

        一眼看去一共三组不重复的表单,且输入字符串应全为一种表单里的元素,那么可以直接利用散列集合(hash set)的特性快速筛选符合要求的字符串。

    private static Set<Character> set1 = new HashSet<>(16), set2 = new HashSet<>(16), set3 = new HashSet<>(16);

    static {
        char[] chars1 = new char[] {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
        char[] chars2 = new char[] {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
        char[] chars3 = new char[] {'z', 'x', 'c', 'v', 'b', 'n', 'm'};
        for (char c : chars1) set1.add(c);
        for (char c : chars2) set2.add(c);
        for (char c : chars3) set3.add(c);
    }

    public String[] findWords(String[] words) {
        ArrayList<String> list = new ArrayList<>();

        for (String word : words) {
            int i = 0, n = word.length();
            Set<Character> set;
            if (set1.contains(getAwfulChar(word.charAt(i)))) {
                set = set1;
            } else if (set2.contains(getAwfulChar(word.charAt(i)))) {
                set = set2;
            } else {
                set = set3;
            }
            while (i < n && set.contains(getAwfulChar(word.charAt(i)))) ++ i;
            if (i == n) list.add(word);

        }

        String[] result = new String[list.size()];
        return list.toArray(result);
    }

    private static char getAwfulChar(char c) {
        if ('a' <= c && c <= 'z') return c;
        else return (char) (c+32);
    }

                ​​​​​​​        ​​​​​​​        ​​​​​​​        

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值