500. Keyboard Row

来源:互联网 发布:鲜活的数据 英文 编辑:程序博客网 时间:2024/06/01 10:40

Given a List of words, return the wordsthat can be typed using letters of alphabet on only one row's of Americankeyboard like the image below.

Example 1:

Input: ["Hello","Alaska", "Dad", "Peace"]

Output: ["Alaska","Dad"]

Note:

You may use one character in the keyboardmore than once.

You may assume the input string will onlycontain letters of alphabet.

谷歌翻译:给定一个单词列表,返回可以使用字母表中的字母输入的字只在美国键盘的一行上,如下图所示。您可以在键盘中多次使用一个字符。您可以假定输入字符串将仅包含字母表字母。

题目的意思是,是否输入的字符串数组中,每一个字符串的每个字符是否都包含在键盘中的三行的任意一行中。例如Alaska的每个字符都在第一行”asdfghjkl”。

这题我是看的参考,也是利用集合,感觉别人把map集合用的很熟练。代码如下:

public class Solution {

    public String[]findWords(String[] words) {

        //设置一个字符串数组存储键盘的三行字符串

           String[]str={"qwertyuiop","asdfghjkl","zxcvbnm"};

           //将字符串数组放入map集合中,value值对应着行数

           Map<Character,Integer>map=new HashMap<>();

           for(inti=0;i<str.length;i++){

                 for(charc:str[i].toCharArray()){

                      map.put(c,i);

                 }

           }

           //设置一个Link存放数组

           List<String>link=new LinkedList();

           for(inti=0;i<words.length;i++){

                 //得到每一个字符串的首字母对应的value值

                 intlen=map.get(words[i].toLowerCase().charAt(0));//看这个字符串在哪一行

                 for(charw:words[i].toLowerCase().toCharArray()){

                      if(map.get(w)!=len){

                            len=-1;

                            break;

                      }

                 }

                 if(len!=-1){

                      link.add(words[i]);

                 }

           }

     /*   Patternp=Pattern.compile("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*",Pattern.CASE_INSENSITIVE);

           List link=new LinkedList();

           for(String s:words){

                 if(p.matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*",s.toLowerCase())){

                      ls.add(s);

                 }

           }*/

           returnlink.toArray(new String[0]);//集合直接转换成数组,必须new String[0]返回字符串数组

    }

}

其中有一个Pattern类,这个在eclipse中是可以运行的,但是通不过。说不能识别Pattern这个类,我是用的正则表达式写的。

 

 

0 0