leetcode500: Keyboard Row

本文介绍了一种算法,用于从给定的字符串数组中筛选出仅使用美国键盘单行字母排列即可输入的单词。通过将键盘上的三行字母分别存储为集合,并检查每个单词的所有字符是否属于同一行来实现。

摘要生成于 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.

注意:这个程序说明如何返回一个String[] 

	public String[] findWords(String[] words) {
		String q1 = "QWERTYUIOP";
		String a1 = "ASDFGHJKL";
		String z1 = "ZXCVBNM";
		ArrayList q = new ArrayList();
		ArrayList a = new ArrayList();
		ArrayList z = new ArrayList();
		List<String> re = new LinkedList<>();
		for (int i = 0; i < q1.length(); i++)
			q.add(q1.charAt(i));
		for (int i = 0; i < a1.length(); i++)
			a.add(a1.charAt(i));
		for (int i = 0; i < z1.length(); i++)
			z.add(z1.charAt(i));
		for (int i = 0; i < words.length; i++) {
			char[] candidate = words[i].toUpperCase().toCharArray();
			boolean flag1 = true;
			boolean flag2 = true;
			boolean flag3 = true;
			for (int j = 0; j < candidate.length; j++) {
				if (q.contains(candidate[j]))
					flag1 = false;
				else if (a.contains(candidate[j]))
					flag2 = false;
				else if (z.contains(candidate[j]))
					flag3 = false;
				else
					break;
			}
			if (((flag1 == false) && (flag2 == true) && (flag3 == true))
					|| ((flag1 == true) && (flag2 == false) && (flag3 == true))
					|| ((flag1 == true) && (flag2 == true) && (flag3 == false)))
				re.add(words[i]);
		}
		return re.toArray(new String[0]);
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值