Leet Code知识点总结 - 500

LeetCode 500. Keyboard Row

考点 难度
Array Easy
题目

Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.

In the American keyboard:

the first row consists of the characters “qwertyuiop”,
the second row consists of the characters “asdfghjkl”, and
the third row consists of the characters “zxcvbnm”.

思路

这道题解法比较多。可以用map,由每个字母map到对应的行数,但是这种方法需要手动输入所以工作量比较大。另一种方法是用string储存键盘上三行的所有字母,再用indexOf( )进行判断。最后的结果需要转换成array。

答案
public String[] findWords(String[] words) {
        String[] rows = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
        List<String> result = new ArrayList();
        for (String w: words) {
            int first = 0, second = 0, third = 0;
            for (char c : w.toCharArray()) {
                if (rows[0].toLowerCase().indexOf(c) != -1) 
                    first++;
                if (rows[1].toLowerCase().indexOf(c) != -1) 
                    second++;
                if (rows[2].toLowerCase().indexOf(c) != -1) 
                    third++;             
            }
            if ((first == 0 && secong == 0) || (first == 0 && third == 0) || (second == 0 && third == 0))
                result.add(w);           
        }
        return result.toArray(new String[0]);
    }

另外还有一种解法不需要遍历word里面的每个字母:先确定word里面第一个字母对应行,如果遇到有字母不在该行则停止循环。代码见nmudunuri的答案

Guess you like

Origin blog.csdn.net/m0_59773145/article/details/120007665