500. Keyboard Row

来源:互联网 发布:win10 预装软件 编辑:程序博客网 时间:2024/06/05 23:55

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.




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.


public class Solution {    public String[] findWords(String[] words) {        Set<Character> first=new HashSet<>();        Set<Character> secend=new HashSet<>();        Set<Character> third=new HashSet<>();                List<String> result = new ArrayList<>();        addword(first,secend,third);        int[] count={0,0,0};        for(int i=0;i<words.length;i++)        {            char[] charArray = words[i].toLowerCase().toCharArray();//大写变小写和转变char数组            for(int j=0;j<words[i].length();j++)//当数据较大时,加快运行速度这里可以加几个if判断是否符合以便随时中断            {                if(first.contains(charArray[j]))count[0]++;                else if(secend.contains(charArray[j]))count[1]++;                else if(third.contains(charArray[j]))count[2]++;            }            if(count[0]==words[i].length()||count[1]==words[i].length()||count[2]==words[i].length())            {                result.add(words[i]);            }            for(int z=0;z<3;z++)            {                count[z]=0;            }        }        return result.toArray(new String[result.size()]);//toArray()将list集合转变成数组形式    }    public void addword(Set<Character> f,Set<Character> s,Set<Character> t){        String x="qwertyuiop",c="asdfghjkl",v="zxcvbnm";        for(Character i:x.toCharArray())//转变char数组        {            f.add(i);        }        for(Character i:c.toCharArray())        {            s.add(i);        }        for(Character i:v.toCharArray())        {            t.add(i);        }    }}

接下来就是大神的代码:

return Stream.of(words).filter(s -> s.toLowerCase().matches("[qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*")).toArray(String[]::new);}



原创粉丝点击