LeetCode: 500. Keyboard Row

本文介绍了一个LeetCode上的编程题目——键盘行单词。该题要求从输入的字符串数组中筛选出仅使用美国键盘同一行字母组成的单词。通过一个Java实现的解决方案,详细展示了如何检查每个单词是否符合要求,并返回符合条件的所有单词。

LeetCode: 500. Keyboard Row

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: You may use one character in the keyboard more than once. You
may assume the input string will only contain letters of alphabet.

public class Solution {
    String[] keyboards = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
    public String[] findWords(String[] words) {
        int[] result = new int[words.length];
        int n = 0;
        for (int j = 0; j < words.length; j++) {
            String wor = words[j].toLowerCase();
            int line = -1;
            for (int i = 0; i < keyboards.length; i++) {
                String one = wor.substring(0, 1);
                if (keyboards[i].contains(one)) {
                    line = i;
                }
            }
            boolean flag = true;
            for (int i = 0; i < wor.length(); i++) {
                if (!keyboards[line].contains(wor.substring(i, i + 1))) {
                    flag = false;
                    break;
                }
            }
            if (flag == true) {
                result[n] = j;
                n++;
            }
        }
        String[] results = new String[n];
        for (int i = 0; i < n ; i++) {
            results[i] = words[result[i]];
        }
        return results;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值