500. Keyboard Row

本文介绍了一种算法,用于从给定的单词列表中筛选出所有字母均可在同一行美国键盘上输入的单词,并提供了完整的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


American keyboard


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.

题意:

判断一个单词的每一个字母是否都来自键盘上的同一行,是的话就放在最终结果的数组中

算法思路:

1.首先用3个字符串数组存放三行的字母

2.然后将三行的字母放到map中,对map设置不同的行设置不同的值

3.取每个单词的首字母进行判断,如果在map中取出的值不相等,flag=0,如果都满足在数组集合中添加这个单词

4.将数组list转化为数组

注意:在取每个单词的字母时,取出的是char类型的,直接get键值拿到的是NULL,所以在前面加上“”用来匹配字符串

代码实现

package easy;

import java.util.ArrayList;
import java.util.HashMap;

public class KeyboardRow {
	public static String[] findWords(String[] words) {
        String[] row1 = {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"};
        String[] row2 = {"a", "s", "d", "f", "g", "h", "j", "k", "l"};
        String[] row3 = {"z", "x", "c", "v", "b", "n", "m"};
        HashMap hashMap = new HashMap();
        ArrayList list = new ArrayList();
        //添加第一行
        for(int i=0; i<row1.length; i++){
        	hashMap.put(row1[i], 1);
        }
        //添加第二行
        for(int i=0; i<row2.length; i++){
        	hashMap.put(row2[i], 2);
        }
        //添加第三行
        for(int i=0; i<row3.length; i++){
        	hashMap.put(row3[i], 3);
        }
        
        for(int i=0; i<words.length; i++){//遍历每一个单词
        	boolean flag = true;
        	for(int j=0; j<words[i].length(); j++){
        		if(hashMap.get("" + words[i].toLowerCase().charAt(0)) != hashMap.get("" + words[i].toLowerCase().charAt(j))){     			
        			flag = false;
        			break;
        		}
        	}
        	if (flag){
        		list.add(words[i]);
        	}
        }
        String[] result = new String[list.size()];
        return (String[])list.toArray(result);
    }
	
	public static void main(String[] args){		
		String[] words = {"Hello", "Alaska", "Dad", "Peace"};
		String[] result = findWords(words);
		for(int i=0; i<result.length; i++){
			System.out.println(result[i]);
		}
	}
}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值