500.键盘行

keyboard-row

题目描述
给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。

示例:

输入: [“Hello”, “Alaska”, “Dad”, “Peace”]
输出: [“Alaska”, “Dad”]

注意:

你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。

代码

public class Solution {
	public String[] findWords(String[] words){
		String[] res;
		if(words.length == 0){
			res = new String[0];
			return res;
		}
		List<String> resList = new ArrayList<>();
		List<Character> first = new ArrayList<>();
		first.add('Q');
		first.add('q');
		first.add('W');
		first.add('w');
		first.add('E');
		first.add('e');
		first.add('R');
		first.add('r');
		first.add('T');
		first.add('t');
		first.add('Y');
		first.add('y');
		first.add('U');
		first.add('u');
		first.add('I');
		first.add('i');
		first.add('O');
		first.add('o');
		first.add('P');
		first.add('p');
		
		List<Character> second = new ArrayList<>();
		second.add('A');
		second.add('a');
		second.add('S');
		second.add('s');
		second.add('D');
		second.add('d');
		second.add('F');
		second.add('f');
		second.add('G');
		second.add('g');
		second.add('H');
		second.add('h');
		second.add('J');
		second.add('j');
		second.add('K');
		second.add('k');
		second.add('L');
		second.add('l');
		
		List<Character> third = new ArrayList<>();
		third.add('Z');
		third.add('z');
		third.add('X');
		third.add('x');
		third.add('C');
		third.add('c');
		third.add('V');
		third.add('v');
		third.add('B');
		third.add('b');
		third.add('N');
		third.add('n');
		third.add('M');
		third.add('m');
		
		for(int i=0;i<words.length;i++){
			//若当前单词由一个字母构成
			if(words[i].length() == 1){
				resList.add(words[i]);
				continue;
			}
			
			char sample = words[i].charAt(0);
			if(first.contains(sample)){
				for(int j=1;j<words[i].length();j++){
					if(!first.contains(words[i].charAt(j))){
						break;
					}
					//比对成功,加入结果集
					if(j==words[i].length()-1){
						resList.add(words[i]);
					}
				}
			}else if(second.contains(sample)){
				for(int j=1;j<words[i].length();j++){
					if(!second.contains(words[i].charAt(j))){
						break;
					}
					//比对成功,加入结果集
					if(j==words[i].length()-1){
						resList.add(words[i]);
					}
				}
			}else{
				for(int j=1;j<words[i].length();j++){
					if(!third.contains(words[i].charAt(j))){
						break;
					}
					//比对成功,加入结果集
					if(j==words[i].length()-1){
						resList.add(words[i]);
					}
				}
			}
			
		}
		
		//将resList中的字符串转为数组
		res = new String[resList.size()];
		for(int i=0;i<resList.size();i++){
			res[i] = resList.get(i);
		}
		
		return res;
	}
}

思考
算法思想比较常规,代码重复的部分比较多,但值得注意的是对各种特殊用例的处理。

性能表现
性能表现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值