LeetCode每日一题:键盘行(No.500)

栏目: 编程工具 · 发布时间: 5年前

给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
复制代码
LeetCode每日一题:键盘行(No.500)

示例:

输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
复制代码

思考:

循环遍历单词列表,先判断每个单词首字母在哪一个键盘行。
然后再遍历单词每个字母,看是否全在这个键盘行内。在则加入结果集List。
复制代码

实现:

class Solution {
    public String[] findWords(String[] words) {
        if (words == null) {
            return null;
        }
        //键盘行
        String lines[] = new String[]{
                "qwertyuiop",
                "asdfghjkl",
                "zxcvbnm"
        };
        
        String[] temp = new String[words.length];
        //转小写
        for (int count = 0; count < words.length; count++) {
            temp[count] = words[count].toLowerCase();
        }
        List<String> resultList = new ArrayList();
        int line;
        for (int i = 0; i < temp.length; i++) {
            //所在键盘行
            line = -1;
            char[] charArray = temp[i].toCharArray();
            //寻找首字母所在键盘行
            for (int j = 0; j < lines.length; j++) {
                if (lines[j].contains(String.valueOf(charArray[0]))) {
                    line = j;
                    break;
                }
            }
            if (line != -1) {
                int k;
                遍历单词所有字母看是否全在该键盘行内
                for (k = 0; k < charArray.length; k++) {
                    if (!lines[line].contains(String.valueOf(charArray[k]))) {
                        break;
                    }
                }
                if (k >= charArray.length) {
                    resultList.add(words[i]);
                }
            } else {
                continue;
            }
        }
        return resultList.toArray(new String[resultList.size()]);
    }
}复制代码

以上所述就是小编给大家介绍的《LeetCode每日一题:键盘行(No.500)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Art of Computer Programming, Volume 4,  Fascicle 3

The Art of Computer Programming, Volume 4, Fascicle 3

Donald E. Knuth / Addison-Wesley Professional / 2005-08-05 / USD 19.99

Finally, after a wait of more than thirty-five years, the first part of Volume 4 is at last ready for publication. Check out the boxed set that brings together Volumes 1 - 4A in one elegant case, and ......一起来看看 《The Art of Computer Programming, Volume 4, Fascicle 3》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具