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:

  1. You may use one character in the keyboard more than once.
  2. You may assume the input string will only contain letters of alphabet.

 

分析:判断给定的字符串数组中满足在键盘中属于同一行的字符串,并返回该数组集合。注意给定的字符串是大小写混合的。

思路:将键盘上三行字符分别保存到三个字符串中,然后判断每个字符串是否都属于同一行。具体的看注释:

class Solution {
    public String[] findWords(String[] words) {
        // 将待对比的数组存入
        String row1 = "qwertyuiop";
        String row2 = "asdfghjkl";
        String row3 = "zxcvbnm";
        // 将符合条件的字符串放入ArrayList,之后转为字符串数组
        ArrayList<String> new_words = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            // 标记是否满足条件
            boolean tt = false;
            // 将要检查的字符串转成小写
            String word = words[i].toLowerCase();
            // 标记字符串属于第几行
            int loop = 0;
            for(int j = 0; j < word.length(); j++){
                char ch = word.charAt(j);
                if(j==0){
                    // 给初始行赋值
                    if(row1.indexOf(ch)!=-1)
                        loop=1;
                    if(row2.indexOf(ch)!=-1)
                        loop=2;
                    if(row3.indexOf(ch)!=-1)
                        loop=3;
                }else {
                    // 若存在不同行,则进行标记,不满足条件,为TRUE
                    if(row1.indexOf(ch)!=-1&&loop!=1){
                        tt=true;
                        break;
                    }
                    if(row2.indexOf(ch)!=-1&&loop!=2){
                        tt=true;
                        break;
                    }
                    if(row3.indexOf(ch)!=-1&&loop!=3){
                        tt=true;
                        break;
                    }
                }
            }
            if (tt) {
                continue;
            }
            new_words.add(words[i]);
        }
     // 将ArrayList转成字符串数组常用套路 String[] ss
= new String[new_words.size()]; new_words.toArray(ss); return ss; } }

 

 

 

posted @ 2017-08-27 10:00  白常福  阅读(157)  评论(0编辑  收藏  举报