Keyboard Line

Given a list of words that can be used to print out only to return in the same row of the keyboard letter word. Keyboard as shown in FIG.

2991872-7c7abf21f53f6c57.png
American keyboard

Example:

<pre>输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
</pre>

note:

  1. You can re-use the same character on the keyboard.
  2. You can assume that the input string will only contain letters.
class Solution {
    public String[] findWords(String[] words) {
        String[] str = new String[]{"QWERTYUIOPqwertyuiop","ASDFGHJKLasdfghjkl","ZXCVBNMzxcvbnm"};
        int strLength = str.length;
        List list = new ArrayList();
        int arrayIndex = -1;
        for(String word : words){//拿到每个输入的单词
            int length = word.length();
            for(int i = 0; i < strLength; i++){//遍历该单词
               if(str[i].contains(word.substring(0,1)))  {//拿该单词的第一个字母初步判断它在哪一行
                   int j = 0;
                   for(; j < length; j++){//遍历该单词的每个字母,不在这一行跳出循环
                    if(!str[i].contains(word.substring(j,j+1))){
                        break;
                    }
                   }
                   if(j == length){//该单词在这一行就添加list
                       arrayIndex++;
                       list.add(word);
                   }
               }
            }
            
        }
        int listSize = list.size();
        String[] array = new String[listSize];
        for(int i = 0; i < listSize; i++){
            array[i] =(String) list.get(i);
        }
        return array;
    }
}

Guess you like

Origin blog.csdn.net/weixin_34293141/article/details/90847425