500. 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.




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);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值